使用Pandas根据不同列中的值填充NaN条目,并以字典为指导 [英] Using Pandas to fill NaN entries based on values in a different column, using a dictionary as a guide
问题描述
我有一个很大的数据框,尝试使用字典作为指导,根据A列中的值填充B列的NaN条目.例如:
I have a large dataframe where I'm trying to populate the NaN entries of column B based on the values in column A, using a dictionary as a guide. For example:
df =
A B
0 Red 628
1 Red 149
2 Red NaN
3 Green 575
4 Green 687
5 Green NaN
6 Blue 159
7 Blue NaN
而字典是(例如)
dict = {"Red": 123, "Green": 456, "Blue": 789}
我很好奇使用Pandas用字典中的相应数字替换每个NaN的最佳方法.我不确定在这种情况下如何使用.fillna()或.isnull()方法.我是Pandas的新手,所以我们感谢您的帮助!谢谢.
I am curious as to the best way to replace each NaN with the corresponding number from the dictionary using Pandas. I'm not sure how to use the .fillna() or .isnull() methods in this situation. I'm new to Pandas so any help is appreciated! Thanks.
推荐答案
使用boolean indexing
map
您的dictionary
在必要时将A
转换为B
值:
Select the relevant rows
using boolean indexing
(see docs), and map
your dictionary
to translate A
to B
values where necessary:
na_map = {"Red": 123, "Green": 456, "Blue": 789}
mask = df.B.isnull()
mask
看起来如下:
0 False
1 False
2 True
3 False
4 False
5 True
6 False
7 True
最后:
df.loc[mask, 'B'] = df.loc[mask, 'A'].map(na_map)
A B
0 Red 628
1 Red 149
2 Red 123
3 Green 575
4 Green 687
5 Green 456
6 Blue 159
7 Blue 789
这篇关于使用Pandas根据不同列中的值填充NaN条目,并以字典为指导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!