[英]return floats instead of ndarray in pandas - 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?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.