Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.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中的Sumifs函数_Python_Pandas - Fatal编程技术网

列表中Python中的Sumifs函数

列表中Python中的Sumifs函数,python,pandas,Python,Pandas,我正在尝试在Excel中实现一个简单的sumif函数。 我的数据框如下所示: Value|CatA|CatB|CatC 0.88 | 1 | 1 | 1 0.25 | 1 | 1 | 4 0.54 | 4 | 2 | 3 0.15 | 3 | 2 | 2 0.14 | 1 | 3 | 2 我想要每个类别的价值总和,从数字1到4: 因此: 我尝试过很多东西,比如groupby等,但似乎都没能成功。任何帮助都将不胜感激 您可以然后: 我们可以在melt new_df = ( d

我正在尝试在Excel中实现一个简单的sumif函数。 我的数据框如下所示:

Value|CatA|CatB|CatC
0.88 | 1  | 1  | 1
0.25 | 1  | 1  | 4
0.54 | 4  | 2  | 3
0.15 | 3  | 2  | 2
0.14 | 1  | 3  | 2
我想要每个类别的价值总和,从数字1到4:

因此:

我尝试过很多东西,比如groupby等,但似乎都没能成功。任何帮助都将不胜感激

您可以然后:

我们可以在
melt

new_df = ( df.melt('Value')
             .groupby(['value','variable'])['Value']
             .sum()
             .unstack(fill_value = 0)
             .rename_axis(columns = None,
                          index = 'Number')
             .reset_index())
print(new_df)
   Number  CatA  CatB  CatC
0       1  1.27  1.13  0.88
1       2  0.00  0.69  0.29
2       3  0.15  0.14  0.54
3       4  0.54  0.00  0.25

另一种方法是使用
pd.crosstab

s = df.melt('Value',value_name='Number')
new_df = pd.crosstab(s.Number, s.variable, s.Value, aggfunc='sum').fillna(0)
new_df.columns.name =''


我不了解情况。你是如何得到0的?@CeliusStingher我想这是因为CatA为0 2'sOh,我刚刚得到它,但这不是一个
sumif
操作,而是一个旋转操作。
new_df = ( df.melt('Value')
             .groupby(['value','variable'])['Value']
             .sum()
             .unstack(fill_value = 0)
             .rename_axis(columns = None,
                          index = 'Number')
             .reset_index())
print(new_df)
   Number  CatA  CatB  CatC
0       1  1.27  1.13  0.88
1       2  0.00  0.69  0.29
2       3  0.15  0.14  0.54
3       4  0.54  0.00  0.25
s = df.melt('Value',value_name='Number')
new_df = pd.crosstab(s.Number, s.variable, s.Value, aggfunc='sum').fillna(0)
new_df.columns.name =''
print(new_df)
        CatA  CatB  CatC
Number                  
1       1.27  1.13  0.88
2       0.00  0.69  0.29
3       0.15  0.14  0.54
4       0.54  0.00  0.25