我有一个groupby对象,看起来像:
Age Pclass fam_size
0.0 3 alone 11.586475
1.0 1 alone 83.210410
2 alone 18.092672
3 alone 7.974073
2.0 1 alone 72.784513
2 alone 12.058114
3 alone 10.317035
3.0 1 alone 39.364014
2 alone 14.625000
3 alone 7.048491
4.0 1 alone 36.562920
2 alone 10.500000
3 alone 7.820000
Name: Fare, dtype: float64
我想在我的原始df中找到满足上述groupby对象中列出的age,Pclass和fam_size条件的行,并用它们的相应值填充新列。那些不应该保留为空。
我正在尝试寻找一种有效的方法来执行此操作,可能是套用,转换,映射,合并或一些简短但没有运气的方法。
IIUC您可以通过以下方式进行操作:
In [299]: df
Out[299]:
a b c d
0 1 1 1 11
1 1 1 2 12
2 1 2 3 13
3 1 2 4 14
4 2 1 5 15
In [300]: g
Out[300]:
a b
1 1 3
2 7
Name: c, dtype: int64
In [301]: df.merge(g.reset_index(), on=['a','b'], how='left',
suffixes=['','_'], indicator=True) \
.rename(columns={'c_':'new'})
Out[301]:
a b c d new _merge
0 1 1 1 11 3.0 both
1 1 1 2 12 3.0 both
2 1 2 3 13 7.0 both
3 1 2 4 14 7.0 both
4 2 1 5 15 NaN left_only
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句