简体   繁体   中英

How to extract a class from column using pandas

In the last column, I am trying to extract and only display a class. For example, 'truck' or 'car'. Do anyone know how to list them?

You can just check if str.contains your search value

df[df['col_name'].str.contains('truck')]

Or use a chained str.get and get the occurrences

df.col1.str.get(0).str.get(0)

Example:

df = pd.DataFrame()
df['col1'] = [[['truck',3, ('a',2)]], [['car', 2, ('b', 2)]]]

    col1
0   [[truck, 3, (a, 2)]]
1   [[car, 2, (b, 2)]]

where

df.col1.str.get(0).str.get(0)

yields

0    truck
1      car
Name: col1, dtype: object

So you can use loc

df.loc[df.col1.str.get(0).str.get(0).eq('truck')]

    col1
0   [[truck, 3, (a, 2)]]

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