简体   繁体   中英

How to select rows with specific string from a column with the type of list Python

I have a python dataframe df with several columns in it. and I want to select rows with specif string from a column names A, and the data type in each cell of A is ['str1','str2','str3'...]. I used df['A'].str.contains('str2')] but it doesn't work. I don't know where is the problem. Should I convert list type to string before I can do filter?

example:

dataframe:

           A                           B       C       D 
  1  [animal,tools,new]               white   nyc      25   
  2  [Italian,restaurant,food]        black   boston   20
  3  [Italian,animal,place]           red     chicago   5
  4  [sky,temp,something]             red     island   90

I wanna choose the rows that only contain 'animal' in column A ideal output:

           A                           B       C       D 
  1  [animal,tools,new]               white   nyc      25
  2  [Italian,animal,place]           red     chicago   5 

I think you can using in

df=pd.DataFrame({'A':[['str1','str2','str3'],['str1']]})
['str2' in x for x in df.A]
Out[28]: [True, False]

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