繁体   English   中英

使用Pandas根据不同列中的值填充NaN条目,并以字典为指导

[英]Using Pandas to fill NaN entries based on values in a different column, using a dictionary as a guide

我有一个很大的数据框,我试图使用字典作为指导,根据A列中的值填充B列的NaN条目。 例如:

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的新手,因此感谢您的帮助! 谢谢。

我认为您的索引看起来有些虚假,以下内容可以满足您的需求:

In [19]:
df['B'] = df.set_index('A')['B'].fillna(d).reset_index()['B']

df
Out[19]:
       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

在这里,我们将索引设置为列“ A”,然后调用fillna传递您的字典,这将使用索引('A')执行查找以返回关联的字典值,然后重置索引并覆盖列“ B”

使用boolean indexing (请参阅docs)选择相关的rows ,并map dictionary以在需要时将A转换为B值:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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