Home > front end >  How can I create a column based on a condition in Pandas
How can I create a column based on a condition in Pandas

Time:03-08

I need to create a new column in Pandas by parsing the values in an existing column. This is the function I've created, which works prefectly with other operators like ==:

def parse_trust_name(row):
    if row["trust"].str.contains('OLYMPIA'):
        val = 'Olympia Trust Company'
    else:
        val = 'Open Account'
    return val

I get the following error message when I run it: 'str' object has no attribute 'str'

I am running the following code to apply the function: master_df["trust_new"] = master_df.apply(parse_trust_name, axis=1)

I thought about using np.where but I don't know how to make it conditional.

How can I fix this function?

CodePudding user response:

See the comment for a one line solution. To fix your function, you'll need to rewrite that if statement.

CodePudding user response:

I figured it out

def parse_trust_name_test(row):
    if 'OLYMPIA' in row["trust"]:
        return 'Olympia Trust Company'
    else:
        return 'Open Account'
  • Related