Home > Blockchain >  fillna() method is not updating column of specified filter criteria with 0 value
fillna() method is not updating column of specified filter criteria with 0 value

Time:02-05

I want to fill missing column of a column in Data Frame with 0 but only for those rows which are satisfying certain condition, lets say a column has income for different countries and this column has missing values across country's, I want to fill missing values only for non UK Market. how to do that? below image will enter image description here

CodePudding user response:

np.where() helps for conditional assignment:

# For testing
import numpy as np
import pandas as pd    
df = pd.DataFrame({'Revenues': [np.nan, 2, np.nan, 1, np.nan, 3],
                   'Country': ['UK', 'FR', 'DE', 'FR', 'UK', 'DE']})
    
    
df['NewRevenues'] = np.where(df['Country'] == 'UK',
                             df['Revenues'].fillna(0),
                             df['Revenues'])

CodePudding user response:

loc also works:

import numpy as np
import pandas as pd    

df = pd.DataFrame({
    'app_tot_annual_incom_am': [1, 2, np.NaN, np.NaN, np.NaN],
    'cust_mkt_cd': ['US', 'UK', 'AU', 'UK', 'CA']
    })
    
df.loc[df.cust_mkt_cd=='UK', 'app_tot_annual_incom_am'] = df.loc[df.cust_mkt_cd=='UK', 'app_tot_annual_incom_am'].fillna(0)

OUTPUT:

app_tot_annual_incom_am cust_mkt_cd
0 1.0 US
1 2.0 UK
2 NaN AU
3 0.0 UK
4 NaN CA
  •  Tags:  
  • Related