如何使用不同的条件填充缺失值
假设我们有以下数据框。我想按列主题和以下条件填充列高度组的空值。
- 如果 Subject 中有一个缺失值,则用另一个值填充该 Subject 的缺失值。
- 如果一个 Subject 中有两个缺失值,则使用 x == 'AA' 的所有受试者的身高中位数来填充这些缺失值
注意:在所需的数据框中,每个主题必须具有相同的值。
df = pd.DataFrame({'Subject': [1,1,2,2,3,3], 'x':['AA','AA','BB','BB','AA','AA'], 'height': [130, np.nan, np.nan, 170, np.nan, np.nan]})
这是所需的数据框。
回答
您可以先fillna()使用分组ffill()和bfill(),然后使用列median:
df.groupby('Subject')['height'].fillna(method='ffill',inplace=True).fillna(method='bfill',inplace=True)
df['height'].fillna(df['height'].median(),inplace=True)
输出:
Subject x height
0 1 AA 130.0
1 1 AA 130.0
2 2 BB 170.0
3 2 BB 170.0
4 3 AA 150.0
5 3 AA 150.0
编辑:如果您要求中位数应采用等于缺失值的 x 值的值,而不是整个数据集的值,您可以使用@xicoaio 的建议并替换我的第二行df['height'].fillna(df['height'].median(),inplace=True):
df['height'] = df.apply(lambda x: x['height'] if x['height'] == np.nan else df[df['x'] == x['x']]['height'].median() , axis=1)
输出:
Subject x height
0 1 AA 130.0
1 1 AA 130.0
2 2 BB 170.0
3 2 BB 170.0
4 3 AA 130.0
5 3 AA 130.0