Here is my df.
I want to get the first value in each column which contains (F)
>>> d = {0: ['1', '2(F)', '6', '8', '5'],
1: ['8(F)', '6', '8', '4(F)', '4'],
2: ['1', '6', '8(F)', '4(F)', '5'],
3: ['1', '8', '8', '1', '5']}
>>> df = pd.DataFrame(data=d)
>>> df
0 1 2 3
0 1 8(F) 1 1
1 2(F) 6 6 8
2 6 8 8(F) 8
3 8 4(F) 4(F) 1
4 5 4 5 5
And the result should look like this
0 2(F)
1 8(F)
2 8(F)
3 NaN
But when I used the code below, I received some errors
>>> mask = df.apply(lambda x: x.str.contains('F'))
>>> a = mask.idxmax().where(mask.any())
>>> print(df[a])
KeyError: '[nan] not in index'
Here is one way
mask = df.applymap(lambda x: '(F)' in x)
df[mask].bfill().iloc[0,]
Out[624]:
0 2(F)
1 8(F)
2 8(F)
3 NaN
Name: 0, dtype: object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With