>>> 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?
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
关于python - 在 Pandas 中返回浮点数而不是ndarray-python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43279267/