Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first occurrence value in each column

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'
like image 849
Webcy Avatar asked Dec 11 '22 02:12

Webcy


1 Answers

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
like image 152
BENY Avatar answered Jan 10 '23 05:01

BENY