返回花车而不是ndarray在熊猫 - python
问题描述:
>>> df=pd.DataFrame({'c1':[1,1,1,1,2,2,2,2],'c2':['a','b','a','b','a','a','b','b'],'c3':['w','w','x','x','w','x','w','x'],'c4':[90,28,31,10,21,55,49,23]})
>>> groups = df.groupby(['c1','c3'])
>>> groups.apply(lambda x: x[x['c2']=='b'].c4.values/x[x['c2']=='a'].c4.values)
c1 c2
1 w [0.31111]
x [0.32258]
2 w [2.33333]
x [0.41818]
有没有办法让上面的操作返回浮动值而不是ndarray?返回花车而不是ndarray在熊猫 - python
c1 c2
1 w 0.31111
x 0.32258
2 w 2.33333
x 0.41818
答
我认为你可以输出转换为Series
:
df = groups.apply(lambda x: pd.Series(x[x['c2']=='b'].c4/x[x['c2']=='a'].c4.values))
.reset_index(level=2, drop=True)
print (df)
c1 c3
1 w 0.311111
x 0.322581
2 w 2.333333
x 0.418182
Name: c4, dtype: float64
它的伟大工程!再次感谢你的帮助! – HappyPy
很高兴能帮到你! – jezrael