【问题标题】:Parsing through dictionary and updating blanks in a dataframe通过字典解析并更新数据框中的空白
【发布时间】:2020-06-16 07:42:41
【问题描述】:

请查看以下数据框:

      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 中编写代码,那就太好了:)

【问题讨论】:

  • 出了什么问题,你在纠结哪一部分?

标签: python pandas numpy dictionary


【解决方案1】:

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

# 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 2021-11-24
    • 1970-01-01
    • 2020-11-24
    • 2021-12-30
    • 1970-01-01
    相关资源
    最近更新 更多