bkcollection
bkcollection

Reputation: 924

Python: Pandas to add a string if the condition is NaN

I want to change is the name column is NaN, I want to add a string 'P' if there is a dash in column symbol.

      name    symbol
0     NaN     Bom
1     John    Madam-T
2     Marry   Madam
3     NaN     Madam-T 
4     NaN     Bom-T
5     NaN     Marry-Y

The desired outcome is

      name    symbol
0     NaN     Bom
1     John    Madam-T
2     Marry   Madam
3     NaN     Madam-PT 
4     NaN     Bom-PT
5     NaN     Marry-PY

Index 3 to 5 will add a string of P as it contains - But I only want it to occurred if the condition of the column name is NaN. df = df['symbol'].str.replace('-', '-P') replace all columns that contains - df = df['name'].isnull call the NaN in column name however, I unable to combine both.

Upvotes: 1

Views: 541

Answers (1)

jezrael
jezrael

Reputation: 863256

Use DataFrame.loc for select and set values filterd by mask:

m = df['name'].isnull()
df.loc[m, 'symbol'] = df.loc[m, 'symbol'].str.replace('-', '-P')
print (df)
    name    symbol
0    NaN       Bom
1   John   Madam-T
2  Marry     Madam
3    NaN  Madam-PT
4    NaN    Bom-PT
5    NaN  Marry-PY

Upvotes: 1

Related Questions