Pandas:用字典引用另一列填充 NaN 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42848911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas: fill in NaN values with dictionary references another column
提问by Natasha
I have a dictionary that looks like this
我有一本看起来像这样的字典
dict = {'b' : '5', 'c' : '4'}
dict = {'b' : '5', 'c' : '4'}
My dataframe looks something like this
我的数据框看起来像这样
A B
0 a 2
1 b NaN
2 c NaN
Is there a way to fill in the NaN values using the dictionary mapping from columns A to B while keeping the rest of the column values?
有没有办法使用从 A 列到 B 列的字典映射来填充 NaN 值,同时保留其余的列值?
回答by Vaishali
You can map dict values inside fillna
您可以在 fillna 内映射 dict 值
df.B = df.B.fillna(df.A.map(dict))
print(df)
打印(df)
A B
0 a 2
1 b 5
2 c 4
回答by abburi
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.
这也可以有效地用于更大的数据集。
回答by 3novak
Unfortunately, this isn't one of the options for a built-in function like pd.fillna()
.
不幸的是,这不是像pd.fillna()
.
Edit: Thanks for the correction. Apparently this is possible as illustrated in @Vaishali's answer.
编辑:感谢您的更正。显然这是可能的,如@Vaishali 的回答所示。
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)