Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.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_Dataframe_Pandas Groupby - Fatal编程技术网

Python 熊猫:如何结合努尼克和森

Python 熊猫:如何结合努尼克和森,python,pandas,dataframe,pandas-groupby,Python,Pandas,Dataframe,Pandas Groupby,我使用的数据帧与此类似: id年度损失收入费用 2 2014 1500 5000 400 1 2013 1000 2000 5600 1 2018 500 10000 2100 3 2019 1500 15000 500 2 2011 100 2100 500 4 2010 1200 400 2000 4 2014 1000 22000 1000 我想按id列中的唯一值进行排序,并找到损

我使用的数据帧与此类似:

id年度损失收入费用
2   2014    1500    5000    400
1   2013    1000    2000    5600
1   2018    500 10000   2100
3   2019    1500    15000   500
2   2011    100 2100    500
4   2010    1200    400 2000
4 2014 1000 22000 1000

我想按
id
列中的唯一值进行排序,并找到
损失
收入
费用
我想要的结果

id损失收入费用
2   1600    7100    900
1   1500    12000   7700
3   1500    15000   500
4 2200 22400 3000

我试着用

df.groupby('id')[“损失”、“收入”、“费用”].sum().reset_index()


但它返回的列比它应该返回的多。我试图利用
nunique()
来获取
id
的唯一值,然后从中获取其余列的总和,但我正在努力找到一种方法使其工作

将参数
sort=False
as_index=False
添加到:

df.groupby('id',as_index=False)[[损失]、[收入]、[费用]].sum()
df = df.groupby('id', sort=False, as_index=False)['losses', 'revenue', 'expenses'].sum()
print (df)
   id  losses  revenue  expenses
0   2    1600     7100       900
1   1    1500    12000      7700
2   3    1500    15000       500
3   4    2200    22400      3000