根据熊猫中的值填充单元格

时间:2019-02-05 17:25:38

标签: python-3.x pandas pandas-groupby

给出以下数据框...

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填充所有行的RaceID

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}}。

1 个答案:

答案 0 :(得分:2)

您可以按ID和填充/填充将数据分组

df1.replace('', np.nan, inplace = True)
df1['Sex'] = df1.groupby('ID').Sex.apply(lambda x: x.ffill().bfill())