根据 ID 列使用来自另一行的值估算 Pandas 数据框列

Impute Pandas dataframe column with value from another row based on ID column

df:

id   name 
0    toto                    
1    tata
0    NaN

我想根据 id 来估算第三行的名称列缺失值。 所需的数据框为:

id   name 
0    toto                    
1    tata
0    toto

我做了以下事情:

df.loc[df.name.isna(), "name"] = df["id"].map(df["name"])

但它不起作用。

import pandas as pd
df = pd.DataFrame({'id':[0,1,0],
              'name':['toto','tata',pd.NA]})

df = df[['id']].merge(df[pd.notna(df['name'])].drop_duplicates(),
                      how = 'left', 
                      on = 'id')
df

如果组内只有一个值,可以试试

df = df.groupby('id').apply(lambda g: g.ffill().bfill())
print(df)

   name
0  toto
1  tata
2  toto

或者将NaN排序到最后

df = (df.sort_values('name')
      .groupby('id').ffill()
      .sort_index())