bac*_*444 4 python dataframe pandas
我想获取字典并使用它来填充数据框列中的缺失值。因此,字典键对应于数据帧中的索引或数据帧中的不同列,字典中的值对应于我想要更新到数据帧中的值。这是一个更直观的例子。
key_col target_col
0 w a
1 c NaN
2 z NaN
Run Code Online (Sandbox Code Playgroud)
我想映射到数据框中的字典
dict = {'c':'B','z':'4'}
Run Code Online (Sandbox Code Playgroud)
我希望数据框看起来像
key_col target_col
0 w a
1 c B
2 z 4
Run Code Online (Sandbox Code Playgroud)
现在我尝试了一些不同的事情。将索引设置为 key_col 然后尝试
df[target_col].map(dict)
df.loc[target_col] = df['key_col'].map(dict)
Run Code Online (Sandbox Code Playgroud)
我知道替换不起作用,因为它要求我对需要替换的值设置标准。如果 key_col/index 有数据值,我只想更新该值。
dict = {'c':'B','z':'4'}
#mask those that are not NaN in `target_col`
m=df.target_col.isna()
df.loc[m,'target_col']=df.key_col.map(dict)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12791 次 |
最近记录: |