2

给定这个例子:

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

我可以遍历hids 和hospitals like的所有组合for hid, hospital in df[["hid", "hospital"]].drop_duplicates().itertuples(index=False),但我不知道下一步该怎么做。

4

1 回答 1

1

groupbyand与andapply结合使用:ffillbfill

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

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

于 2018-08-28T09:58:07.673 回答