首页 > 解决方案 > 通过字典解析并更新数据框中的空白

问题描述

请查看以下数据框:

      A     B
0     Fruit Apple
1     Car   BMW
2           Cat

字典:{'Apple': 'Fruit', 'BMW':'Car','Cat': 'Animal'}

期望的输出:

      A      B
0     Fruit  Apple
1     Car    BMW
2     Animal Cat

我的想法:

  1. 解析 A 列
  2. 识别空白值
  3. 对于每个空白值,查看“B”列中对应的行元素(例如:“”->“猫”)
  4. 从该行获取值并用作标记为“字典”的已定义字典的键
  5. 使用键值对的输出值,并将空白值替换为字典的输出值

如果有人可以帮我在 python 中编写这个代码,那就太好了:)

标签: pythonpandasnumpydictionary

解决方案


如果你的 DataFrame 和字典被命名为dfand d,试试这个:

# Map column B to values of the dictionary
mapper = df['B'].map(d)

# Replace empty strings in A with corresponding dict-mapped value
df['A'] = df['A'].replace('', np.nan).fillna(mapper)

df
        A      B
0   Fruit  Apple
1     Car    BMW
2  Animal    Cat

推荐阅读