df1是具有4列的数据帧。在
我想创建一个新的数据帧(df2),方法是将列“a”分组为df1,并对列“C”和“D”执行多列操作
“AA”列=平均值(C)+平均值(D)
“BB”列=标准(D)
df1= pd.DataFrame({
'A' : ['foo', 'bar', 'foo', 'bar','foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three','two', 'two', 'one', 'three'],
'C' : np.random.randn(8),
'D' : np.random.randn(8)})
A B C D
0 foo one 1.652675 -1.983378
1 bar one 0.926656 -0.598756
2 foo two 0.131381 0.604803
3 bar three -0.436376 -1.186363
4 foo two 0.487161 -0.650876
5 bar two 0.358007 0.249967
6 foo one -1.150428 2.275528
7 foo three 0.202677 -1.408699
def fun1(gg): # this does not work
return pd.DataFrame({'AA':C.mean()+gg.C.std(), 'BB':gg.C.std()})
dg1 = df1.groupby('A')
df2 = dg1.apply(fun1)
这不起作用。似乎aggregation()只适用于序列,而多列操作是不可能的。 而apply()只能通过多列操作生成序列输出。 有没有其他方法可以用多列操作产生多列输出(DataFrame)?在
你的}
f
函数有没有打字错误?AA
应该是C.mean() + C.std()
还是{在第一种情况下,
AA
=C.mean() + C.std()
对于第二个问题
^{pr2}$C.mean() + D.mean()
,情况并没有那么好。当您给groupby对象上的.agg
函数一个dict时,我认为没有办法从两列中获取值。在您可能需要将g.mean()和g.std()分配给临时变量,以避免计算它们两次。在
相关问题 更多 >
编程相关推荐