简体   繁体   中英

How to filter a transposed pandas dataframe?

Say I have a transposed df like so

    id       0          1           2            3
0  1361     Spain     Russia     South Africa   China
1  1741     Portugal  Cuba       UK             Ukraine
2  1783     Germany   USA        France         Egypt
3  1353     Brazil    Russia     Japan          Kenya
4  1458     India     Romania    Holland        Nigeria

How could I get all rows where there is 'er' so it'll return me this

   id       0           1           2            3
2  1783     Germany   USA        France         Egypt
4  1458     India     Romania    Holland        Nigeria

because 'er' is contained in Germany and Nigeria.

Thanks!

Using contains

df[df.apply(lambda x :x.str.contains(pat='er')).any(1)]
Out[96]: 
             id        0        1        2     3
2 1783  Germany      USA   France    Egypt  None
4 1458    India  Romania  Holland  Nigeria  None

Use apply + str.contains across rows:

df = df[df.apply(lambda x: x.str.contains('er').any(), axis=1)]

print(df)
     id        0        1        2        3
2  1783  Germany      USA   France    Egypt
4  1458    India  Romania  Holland  Nigeria

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM