I have created the following pandas dataframe
import pandas as pd
import numpy as np
ds = {
'col1' :
[
['U', 'U', 'U', 'U', 'U', 1, 0, 0, 0, 'U','U', None],
[6, 5, 4, 3, 2],
[0, 0, 0, 'U', 'U'],
[0, 1, 'U', 'U', 'U'],
[0, 'U', 'U', 'U', None]
]
}
df = pd.DataFrame(data=ds)
The dataframe looks like this:
print(df)
col1
0 [U, U, U, U, U, 1, 0, 0, 0, U, U, None]
1 [6, 5, 4, 3, 2]
2 [0, 0, 0, U, U]
3 [0, 1, U, U, U]
4 [0, U, U, U, None]
For each row in col1
, I need to check if every element equals to U
in the list is followed (from left to right) by any value apart from U
and None
: in that case I'd create a new column (called iCount
) with value of 1. Else 0.
In the example above, the resulting dataframe would look like this:
col1 iCount
0 [U, U, U, U, U, 1, 0, 0, 0, U, U, None] 1
1 [6, 5, 4, 3, 2] 0
2 [0, 0, 0, U, U] 0
3 [0, 1, U, U, U] 0
4 [0, U, U, U, None] 0
Only in the first row the value U
is followed by a value which is neither U
nor None
(it is 1
)
I have tried this code:
col5 = np.array(df['col1'])
for i in range(len(df)):
iCount = 0
for j in range(len(col5[i])-1):
print(col5[i][j])
if((col5[i][j] == "U") & ((col5[i][j+1] != None) & (col5[i][j+1] != "U"))):
iCount += 1
else:
iCount = iCount
But I get this (wrong) dataframe:
col1 iCount
0 [U, U, U, U, U, 1, 0, 0, 0, U, U, None] 0
1 [6, 5, 4, 3, 2] 0
2 [0, 0, 0, U, U] 0
3 [0, 1, U, U, U] 0
4 [0, U, U, U, None] 0
Can anyone help me please?
[U, U, 4, U, U, 1, 0, 0, 0, U, U, None, 1, U, None]
[U, None, 1, U]
?