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?
            Asked
            
        
        
            Active
            
        
            Viewed 102 times
        
    0
            
            
        - 
                    41- clean your screen, 2- please do not post images of data/code but **text**: [how to ask pandas questions](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – mozway Feb 05 '22 at 12:42
- 
                    Did you literally take a picture of your screen ? :D – AloneTogether Feb 05 '22 at 13:32
2 Answers
0
            
            
        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'])
 
    
    
        Hervé Mignot
        
- 281
- 3
- 3
0
            
            
        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 | 
 
    
    
        quasi-human
        
- 1,898
- 1
- 2
- 13
