如果其他列中的值相同,则向前或向后填充NA

时间:2018-08-28 09:54:46

标签: python pandas missing-data fillna

给出以下示例:

import pandas as pd
df = pd.DataFrame({
    "date": ["20180724", "20180725", "20180731", "20180723", "20180731"],
    "identity": [None, "A123456789", None, None, None],
    "hid": [12345, 12345, 12345, 54321, 54321],
    "hospital": ["A", "A", "A", "B", "B"],
    "result": [70, None, 100, 90, 78]
})

由于前三行具有相同的hidhospital,因此identity中的值也应该相同。至于其他两行,它们也具有相同的hidhospital,但是没有提供已知的identity,因此identity中的值应保持缺失。换句话说,所需的输出是:

       date    identity    hid hospital  result
0  20180724  A123456789  12345        A    70.0
1  20180725  A123456789  12345        A     NaN
2  20180731  A123456789  12345        A   100.0
3  20180723        None  54321        B    90.0
4  20180731        None  54321        B    78.0

我可以遍历hidhospital之类的所有组合,例如for hid, hospital in df[["hid", "hospital"]].drop_duplicates().itertuples(index=False),但是我不知道下一步该怎么做。

1 个答案:

答案 0 :(得分:1)

groupbyapplyffillbfill结合使用:

df['identity'] = df.groupby(['hid', 'hospital'])['identity'].apply(lambda x: x.ffill().bfill())

这将向前填充NaN,向后填充,同时分隔指定组的值。

相关问题