当每个农场有1-4个品种,但不能是同一个农场中具有相同的variety指数的两个品种时,如何从同列中填充缺失的ripening值?假设列包含所有可能的方案。
例如,在下面的样本中,“帝国”和“蜂蜜脆”具有相同的ripening,但它们来自不同的农场。
一个示例df (较大数据帧的一部分):
df = pd.DataFrame(
{'farm': [419,382, 382, 382, 411, 411, 411],
'variety': ['Gala', 'Gala', 'Empire', '', 'Honeycrisp', '', 'Fuji'],
'ripening':[2,2,3,3,3,3,6],
'D': np.random.randn(7)*10,
'E': list('abcdefg')
}
)
df
Out[223]:
farm variety ripening D E
0 419 Gala 2 12.921246 a
1 382 Gala 2 -2.776150 b
2 382 Empire 3 3.551226 c
3 382 3 2.715187 d
4 411 Honeycrisp 3 -13.557640 e
5 411 3 -11.525100 f
6 411 Fuji 6 -3.660661 g我想要的输出:
farm variety ripening D E
0 419 Gala 2 12.921246 a
1 382 Gala 2 -2.776150 b
2 382 Empire 3 3.551226 c
3 382 Empire 3 2.715187 d
4 411 Honeycrisp 3 -13.557640 e
5 411 Honeycrisp 3 -11.525100 f
6 411 Fuji 6 -3.660661 g发布于 2021-10-06 05:40:50
使用:
#create NaNs instead empty strings
df['variety'] = df['variety'].replace('', np.nan)
#test if only 1 unique category per ripening and farm
m = m = df.groupby(['farm','ripening'])['variety'].transform('nunique').eq(1)
#only for filtered rows forward filling values per groups
df.update(df[m].groupby(['farm','ripening'])['variety'].ffill())
print (df)
farm variety ripening D E
0 419 Gala 2 -12.571434 a
1 382 Gala 2 1.839992 b
2 382 Empire 3 18.946881 c
3 382 Empire 3 6.552552 d
4 411 Honeycrisp 3 11.755782 e
5 411 Honeycrisp 3 11.272973 f
6 411 Fuji 6 7.416918 ghttps://stackoverflow.com/questions/69460270
复制相似问题