jeudi 23 janvier 2020

Python: find string in multiple columns and return it in new column

Hi I have an excel data with multiple columns and i need to fined specific word and return it in new column the table look like this:

ID   col0  col1  col2  col3  col4  col5
1    jack  a/h   t/m   w/n   y/h    56
2    sam   z/n   b/w   null  null   93
3    john  b/i   y/d   p/d   null   33

I want to look for 'b' in columns col1, col2, col3, and col4 and create a new column called "b" where the value the cell value with be is returned

the result would look like this

ID   col0  col1  col2  col3  col4  col5  b
1    jack  a/h   t/m   w/n   y/h    56   -
2    sam   z/n   b/w   null  null   93   b/w
3    john  b/i   y/d   p/d   null   33   b/i

and I need an efficient way to do it I tried to use where like this

df1 = df[['col1', 'col2', 'col3', 'col4']]

df1['b']==[x for x in df1.values[0] if any(b for b in lst if b in str(x))]

I got this from this answer https://stackoverflow.com/a/50250103/3105140

yet it is not working for me snice I have null value and rows where the condition do not work

Aucun commentaire:

Enregistrer un commentaire