我有一个数据帧df
,其中包含一个用于postal codes
的列和一个用于district
名称的列。同一行上的postal code
和district
名称形成"现实生活"组合,例如{'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 code
和district
名称的组合上搜索数据帧。
如果找到组合并且都相同,我想将找到的组合中缺少的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
将被放置在末尾并准备向前填充。