Home > Net >  Python change NaN value with df.loc
Python change NaN value with df.loc

Time:05-12

Hi everyone I've an excel sheet that i read with pandas. This is the output :

                              vlan  ajout
0  Vlan Controleur Wifi\nVlan bleu    NaN
1                         Vlan TAM    NaN
2                          Vlam EM    NaN
3  Vlan Controleur Wifi\nVlan bleu    NaN

I'd like to change NaN values to "vlan 10" when in the column "vlan" is find the word "Controleur". The futur output i like to have is :

                              vlan  ajout
0  Vlan Controleur Wifi\nVlan bleu    vlan 10
1                         Vlan TAM    
2                          Vlam EM    
3  Vlan Controleur Wifi\nVlan bleu    vlan 10

At the moment i tried many and many possibilites and i have this code that is the closer to the reality that i can find :

df = pd.read_excel (r'.\test.xlsx')
df['ajout'] = df['ajout'].fillna(0)
df.loc[df['vlan'] == "Controleur", df['ajout']] = 'vlan 10'
print(df)

Sadly it doesn't work and the output is really bad

                              vlan  ajout  0.0  0.0  0.0  0.0
0  Vlan Controleur Wifi\nVlan bleu    0.0  NaN  NaN  NaN  NaN
1                         Vlan TAM    0.0  NaN  NaN  NaN  NaN
2                          Vlam EM    0.0  NaN  NaN  NaN  NaN
3  Vlan Controleur Wifi\nVlan bleu    0.0  NaN  NaN  NaN  NaN

I don't know why so many columns are added and why my 'ajout' column stay fixed to 0

If someone has an idea or a lead, i'll take it

Thanks everyone

CodePudding user response:

You need to find Controleur in Series value

df.loc[df['vlan'].str.contains("Controleur"), 'ajout'] = 'vlan 10'

You can also try df.mask and np.where

df['ajout'] = df['ajout'].mask(df['vlan'].str.contains("Controleur"), 'vlan 10')

# or

df['ajout'] = np.where(df['vlan'].str.contains("Controleur"), 'vlan 10', df['ajout'])
  • Related