Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按差和和分组_Python_Pandas - Fatal编程技术网

Python 按差和和分组

Python 按差和和分组,python,pandas,Python,Pandas,在这里,我创建了一个用于测试的数据帧: columns = ['A','B', 'C'] data = np.array([[1,2,2] , [1,5,4], [7,8,18]]) df_1 = pd.DataFrame(data,columns=columns) df_1 这使得: A B C 0 1 2 2 1 1 5 4 2 7 8 18 要计算“C”列和“B”列之间的差异,我使用: df_2 = pd.DataFrame(df_1

在这里,我创建了一个用于测试的数据帧:

columns = ['A','B', 'C']
data = np.array([[1,2,2] , [1,5,4], [7,8,18]])
df_1 = pd.DataFrame(data,columns=columns)
df_1
这使得:

    A   B   C
0   1   2   2
1   1   5   4
2   7   8   18
要计算“C”列和“B”列之间的差异,我使用:

df_2 = pd.DataFrame(df_1.apply(lambda x : x['C'] - x['B'] , axis = 1))
df_2
这使得:

0   0
1   -1
2   10
如何按列A对差异进行分组和求和,因此返回以下dataframe>:

1   -1
2   10
以下是我的尝试:

df_1.groupby( [ "A"] ).apply(lambda x : x['C'] - x['B'] , axis = 1).sum()
但返回错误:

/opt/conda/lib/python3.6/site-packages/pandas/core/groupby.py in f(g)
    705                 def f(g):
    706                     with np.errstate(all='ignore'):
--> 707                         return func(g, *args, **kwargs)
    708             else:
    709                 raise ValueError('func must be a callable if args or '

TypeError: <lambda>() got an unexpected keyword argument 'axis'
f(g)中的
/opt/conda/lib/python3.6/site-packages/pandas/core/groupby.py
705 def f(g):
706,带有np.errstate(all='ignore'):
-->707返回函数(g,*args,**kwargs)
708其他:
709 raise VALUERROR('如果参数为或,则func必须是可调用的'
TypeError:()获得意外的关键字参数“axis”

我想你需要先减去,然后用
系列
进行
groupby

df2 = (df_1['C'] - df_1['B']).groupby(df_1['A']).sum().reset_index(name='sum')
print (df2)
   A  sum
0  1   -1
1  7   10
使用
应用的解决方案
-在lambda函数中添加
求和

但它在较大的
df
中速度较慢

df2 = df_1.groupby("A").apply(lambda x : (x['C'] - x['B']).sum()).reset_index(name='sum')
print (df2)
   A  sum
0  1   -1
1  7   10
计时

np.random.seed(455)
columns = ['A','B', 'C']
data = np.array(np.random.randint(1000, size=(1000,3)))
df_1 = pd.DataFrame(data,columns=columns)
print(df_1.head())
       A    B    C
0    789  144  421
1    392   27   95
2    960  235  750
3    300  607  422
4    363  397  252

In [154]: %timeit (df_1['C'] - df_1['B']).groupby(df_1['A']).sum().reset_index(name='sum')
100 loops, best of 3: 3.07 ms per loop

In [155]: %timeit df_1.groupby("A").apply(lambda x : (x['C'] - x['B']).sum()).reset_index(name='sum')
1 loop, best of 3: 175 ms per loop