简体   繁体   中英

Pandas Fill Column with Dictionary

I have a data frame like this:

   A    B    C    D    
0  1    0   nan  nan  
1  8    0   nan  nan  
2  8    1   nan  nan  
3  2    1   nan  nan  
4  0    0   nan  nan  
5  1    1   nan  nan  

and i have a dictionary like this:

dc = {'C': 5, 'D' : 10}

I want to fill the nan values in the data frame with the dictionary but only for the cells in which the column B values are 0, i want to obtain this:

   A    B    C    D    
0  1    0    5    10
1  8    0    5    10
2  8    1   nan  nan  
3  2    1   nan  nan  
4  0    0    5    10
5  1    1   nan  nan 

I know how to subset the dataframe but i can't find a way to fill the values with the dictionary; any ideas?

You could use fillna with loc and pass your dict to it:

In [13]: df.loc[df.B==0,:].fillna(dc)
Out[13]:
   A  B  C   D
0  1  0  5  10
1  8  0  5  10
4  0  0  5  10

To do it for you dataframe you need to slice with the same mask and assign the result above to it:

df.loc[df.B==0, :] = df.loc[df.B==0,:].fillna(dc)

In [15]: df
Out[15]:
   A  B   C   D
0  1  0   5  10
1  8  0   5  10
2  8  1 NaN NaN
3  2  1 NaN NaN
4  0  0   5  10
5  1  1 NaN NaN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM