【问题标题】:Pandas: fill missing value based on combination in dataframe熊猫:根据数据框中的组合填充缺失值
【发布时间】:2017-08-21 04:15:36
【问题描述】:

我有一个 DataFrame df 包含 i.a. postal codes 的列和 district 名称的列。同一行上的 postal codedistrict 名称形成“现实生活”组合,例如{'postal code': '10001', 'district':'North'}

对于某些postal code 条目,缺少district 名称。但是,缺少 district 名称的 postal code 可能会与其 district 名称一起出现在数据框中的其他位置。即,

| postal code |   district  |
-----------------------------
|   10001     |    North    |
|   10002     |    West     |
|   10001     |   missing   |

如果postal code 缺少district 名称,我想在DataFrame 中搜索该特定postal codedistrict 名称的组合。

如果找到组合并且都相同,我想用找到的组合中的district 名称替换缺少的district 名称。 如果找到组合,但并不完全相同(例如postal code 与两个区域重叠),我不想替换。

我该怎么做?

【问题讨论】:

    标签: python pandas search replace row


    【解决方案1】:
    df = df.replace('missing', np.nan).sort_values(['postal code', 'district'])
    df.groupby('postal code').ffill().sort_index()
    
       postal code district
    0        10001    North
    1        10002     West
    2        10001    North
    

    我之所以排序是因为np.nan 将被放置在最后并准备好向前填充。

    【讨论】:

    • 谢谢。像魅力一样工作!
    • @LucSpan 很高兴我能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 2016-10-31
    • 2018-03-13
    • 2019-08-01
    相关资源
    最近更新 更多