简体   繁体   中英

Add column containing list value if column contains string in list

I'm trying to scan a particular column in a dataframe, eg df['x'] for values which I have in a separate list list = ['y', 'z', 'a', 'b'] . How do I make pandas load a new column with the list value if df['x'] contains any, or more than one of the values from the list?

Thanks!

Use this:

In [720]: import pandas as pd
In [719]: if df['x'].str.contains('|'.join(list)).any(): 
     ...:     df = pd.concat([df, pd.DataFrame(list)], axis=1)) 
     ...:      

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