我有以下问题
我需要替换数据框中的 NaN 值
df1 = pd.DataFrame([[1001, np.NaN], [1001,'C'], [1004, 'D'],[1005, 'C'],
[1005,'D'], [1010, np.NaN],[1010,np.NaN],[1010,'F']], columns=['CustomerNr','Costs'])
客户编号 | 费用 |
---|---|
1001 | 南 |
1004 | D |
1005 | C |
1010 | 南 |
1010 | 南 |
我试过:
df2 = pd.DataFrame([[1001, 'X'], [1010, 'Y']], columns=['CustomerNr','New Costs'])
期望的输出:
客户编号 | 费用 |
---|---|
1001 | X |
1004 | D |
1005 | C |
1010 | Y |
1010 | Y |
我想你可以用这样的东西
import pandas as pd
import numpy as np
df1 = pd.DataFrame([[1001, np.NaN], [1001,'C'], [1004, 'D'],[1005, 'C'],
[1005,'D'], [1010, np.NaN],[1010,np.NaN],[1010,'F']], columns=['CustomerNr','Costs'])
replace_dict = {1001:"X",1010:"Y"}
df1['Costs'] = df1.apply(lambda x: replace_dict.get(x['CustomerNr']) if pd.isna(x['Costs']) else x['Costs'], axis=1)
解释:创建一个字典(
replace_dict
)映射值分配基于CustomerNr
列的值,如果apply.()
中的值是CustomerNr
,则使用nan
分配这些值,否则应用Costs
的原始值
NA/NaN
值基于系列映射(在匹配的 'CustomerNr'
值上):
df1['Costs'].fillna(df1['CustomerNr']
.map(df2.set_index('CustomerNr')['New Costs']), inplace=True)
CustomerNr Costs
0 1001 X
1 1001 C
2 1004 D
3 1005 C
4 1005 D
5 1010 Y
6 1010 Y
7 1010 F