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

Python 如果其他列中的值相同,则向前或向后填充NAs,python,pandas,missing-data,fillna,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",

举个例子:

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]
})
由于前三行具有相同的
hid
hospital
,因此
identity
中的值也应该相同。至于其他两行,它们也有相同的
hid
hospital
,但没有提供已知的
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

我可以循环使用
hid
s和
hospital
s的所有组合,如
for hid,df中的hospital[[“hid”,“hospital”]。\drop_duplicates().itertuples(index=False)
,但我不知道下一步该怎么做。

使用
groupby
ffill
bfill结合使用
:

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

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

我的问题似乎不够完整,无法复制我的问题。对此我很抱歉。你介意看看我的编辑,看看你的答案是否有变化吗?@ytu:没问题。我调整了答案,看看它是否适合你。