给出以下数据框...
Key ID Type Group1 Group2 Group3 Group4 Sex Race
1 A1 Type 1 x x x x Male White
2 A1 Type 2 x x x x
3 A2 Type 1 Male Black
4 A2 Type 2
5 A3 Type 1 x x x x Female White
6 A3 Type 2 x x x x
7 A3 Type 3 x x x x
8 A3 Type 4 x x x x
如何基于Sex
填充所有行的Race
和ID
?
Key ID Type Group1 Group2 Group3 Group4 Sex Race
1 A1 Type 1 x x x x Male White
2 A1 Type 2 x x x x Male White
3 A2 Type 1 Male Black
4 A2 Type 2 Male Black
5 A3 Type 1 x x x x Female White
6 A3 Type 2 x x x x Female White
7 A3 Type 3 x x x x Female White
8 A3 Type 4 x x x x Female White
我知道我可以使用类似df.loc[df['ID'] == A1, 'Sex'].iloc[0]
的方法来获取特定Sex
的{{1}},但是不确定如何根据以下条件填充ID
的所有空格每个Sex
的{{1}}。
答案 0 :(得分:2)
您可以按ID和填充/填充将数据分组
df1.replace('', np.nan, inplace = True)
df1['Sex'] = df1.groupby('ID').Sex.apply(lambda x: x.ffill().bfill())