Pandas: fill in NaN values with dictionary references another column

后端 未结 3 1598
挽巷
挽巷 2020-12-05 20:07

I have a dictionary that looks like this

dict = {\'b\' : \'5\', \'c\' : \'4\'}

My dataframe looks something like this

   A  B
0          


        
相关标签:
3条回答
  • 2020-12-05 20:44

    Unfortunately, this isn't one of the options for a built-in function like pd.fillna().

    Edit: Thanks for the correction. Apparently this is possible as illustrated in @Vaishali's answer.

    However, you can subset the data frame first on the missing values and then apply the map with your dictionary.

    df.loc[df['B'].isnull(), 'B'] = df['A'].map(dict)
    
    0 讨论(0)
  • 2020-12-05 20:48

    You can map dict values inside fillna

    df.B = df.B.fillna(df.A.map(dict))
    

    print(df)

        A   B
    0   a   2
    1   b   5
    2   c   4
    
    0 讨论(0)
  • 2020-12-05 21:06

    This can be done simply

    df['B'] = df['B'].fillna(df['A'].apply(lambda x: dict.get(x)))
    

    This can work effectively for a bigger dataset as well.

    0 讨论(0)
提交回复
热议问题