简体   繁体   中英

How to match a pandas DataFrame column consisting of a list?

I have a pandas DataFrame whose column is consisted of a list.

For example:

df = pd.DataFrame({'col1': [['a'], ['b'], ['a'], ['b']]})
df
    col1
0   [a]
1   [b]
2   [a]
3   [b]

I want to select those rows that are ['a'], but if I run this code:

df['col1'] == ['a']

I get an error:

ValueError: ('Lengths must match to compare', (4,), (1,))

(Same to code df[df['col1'] == ['a']] )

What proper code should I use to achieve this?

Try following

df[df['col1'].str[0]=='a']

Use:

df = df[df['col1'].apply(lambda x: x == ['a'])]
print (df)
  col1
0  [a]
2  [a]

You can also convert to a string:

out = df[df['col1'].astype(str) == "['a']"]

Output:

  col1
0  [a]
2  [a]

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