简体   繁体   中英

Create new column if DataFrame contains specific string

I have one column in the DataFrame that is a name. Inside this name there are patterns that I want to locate, and create a category in other column of same DataFrame . For example :

Name 

name first RB LA a 
name LB second
RB name third
name LB fourth 

I want the name with the same pattern to be in the same category, displayed in the other column

What I want :

       Name                  Example          

name first RB LA a          Round Blade category
name LB second              Long Biased category
RB name third               Round Blade category
name LB fourth              Long Biased category

I have a DataFrame , not a list, there are several other columns in it. And there are not only two categories, but several ones.

What I have Tried :

df.loc[df['Name']=="RB", 'Example'] = "RB category"

But it does not work since it must be an exact match

Another attempt :

if df[['Name'].str.contains("RB")] : 
    (...)

But it gives me error :

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I tried to add to .bool() or .any() , but or the error persist or nothing happens when I run the line.

Thank you.

You could use pandas.Series.str.extract to achieve the desired output


import numpy as np
import pandas as pd


df = pd.DataFrame({
    "Name": ["name first RB LA a", "name LB second", "RB name third", "name LB fourth"]
})
df["Example"] = df["Name"].str.extract("(LB|RB)")[0] + " category"

    Name                Example
0   name first RB LA a  RB category
1   name LB second      LB category
2   RB name third       RB category
3   name LB fourth      LB category

Edit

To change category names within Example column use .str.replace :

df["Example"] = (df["Example"]
 .str.replace("RB", "Round Blade")
 .str.replace("LB", "Long Biased")
)

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