熊猫:根据数据框中的组合填充缺失值



我有一个数据帧df,其中包含一个用于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名称,我想在具有该特定postal codedistrict名称的组合上搜索数据帧。

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

我该怎么做?

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将被放置在末尾并准备向前填充。

最新更新