获取总计熊猫列


107

目标

我有一个Pandas数据框,如下所示,具有多个列,并希望获取列的总数MyColumn


数据框 -df

print df

           X           MyColumn  Y              Z   
0          A           84        13.0           69.0   
1          B           76         77.0          127.0   
2          C           28         69.0           16.0   
3          D           28         28.0           31.0   
4          E           19         20.0           85.0   
5          F           84        193.0           70.0   

我的尝试

我试图使用groupby和获得列的总和.sum()

Total = df.groupby['MyColumn'].sum()

print Total

这将导致以下错误:

TypeError: 'instancemethod' object has no attribute '__getitem__'

预期产量

我期望输出如下:

319

或者,我想df用一个包含总数的新row标题进行编辑TOTAL

           X           MyColumn  Y              Z   
0          A           84        13.0           69.0   
1          B           76         77.0          127.0   
2          C           28         69.0           16.0   
3          D           28         28.0           31.0   
4          E           19         20.0           85.0   
5          F           84        193.0           70.0   
TOTAL                  319

11
为了说明为什么pandas不是pythonic,除了对如何简单地汇总一列的困惑之外,别无他法。
user1416227

Answers:


213

您应该使用sum

Total = df['MyColumn'].sum()
print (Total)
319

然后loc与一起使用Series,在这种情况下,索引应设置为与您需要求和的特定列相同:

df.loc['Total'] = pd.Series(df['MyColumn'].sum(), index = ['MyColumn'])
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

因为如果传递标量,则将填充所有行的值:

df.loc['Total'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A        84   13.0   69.0
1        B        76   77.0  127.0
2        C        28   69.0   16.0
3        D        28   28.0   31.0
4        E        19   20.0   85.0
5        F        84  193.0   70.0
Total  319       319  319.0  319.0

另有两个解决方案atix请参见下面的应用程序:

df.at['Total', 'MyColumn'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

df.ix['Total', 'MyColumn'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

注意:自Pandas v0.20起,ix已弃用。使用lociloc代替。


太好了:)感谢您的解释,请问.loc以上示例中的内容是什么?
LearningToJava

loc用于放大设置
jezrael

at也可用于放大设置,请参见最后编辑。
jezrael

谢谢,有什么首选的方法吗?
LearningToJava

1
嗯,文档说The .loc/.ix/[] operations can perform enlargement when setting a non-existant key for that axis.,如此locix[]。在接下来的部分是写at may enlarge the object in-place as above if the indexer is missing.那么所有的方法都是好的,但是at是最快的,我认为。
jezrael

22

您可以在此处使用的另一种选择:

df.loc["Total", "MyColumn"] = df.MyColumn.sum()

#         X  MyColumn      Y       Z
#0        A     84.0    13.0    69.0
#1        B     76.0    77.0   127.0
#2        C     28.0    69.0    16.0
#3        D     28.0    28.0    31.0
#4        E     19.0    20.0    85.0
#5        F     84.0   193.0    70.0
#Total  NaN    319.0     NaN     NaN

您也可以使用append()方法:

df.append(pd.DataFrame(df.MyColumn.sum(), index = ["Total"], columns=["MyColumn"]))

在此处输入图片说明


更新:

如果需要为所有数字列追加总和,则可以执行以下操作之一:

用于append以功能性方式执行此操作(不更改原始数据帧):

# select numeric columns and calculate the sums
sums = df.select_dtypes(pd.np.number).sum().rename('total')

# append sums to the data frame
df.append(sums)
#         X  MyColumn      Y      Z
#0        A      84.0   13.0   69.0
#1        B      76.0   77.0  127.0
#2        C      28.0   69.0   16.0
#3        D      28.0   28.0   31.0
#4        E      19.0   20.0   85.0
#5        F      84.0  193.0   70.0
#total  NaN     319.0  400.0  398.0

用于loc在适当位置更改数据框:

df.loc['total'] = df.select_dtypes(pd.np.number).sum()
df
#         X  MyColumn      Y      Z
#0        A      84.0   13.0   69.0
#1        B      76.0   77.0  127.0
#2        C      28.0   69.0   16.0
#3        D      28.0   28.0   31.0
#4        E      19.0   20.0   85.0
#5        F      84.0  193.0   70.0
#total  NaN     638.0  800.0  796.0

所有列的总和如何?
FaCoffee

9

与获取数据框的长度类似len(df),以下内容适用于熊猫和大火:

Total = sum(df['MyColumn'])

或者

Total = sum(df.MyColumn)
print Total

2

列求和有两种方法

数据集= pd.read_csv(“ data.csv”)

1:总和(dataset.Column_name)

2:数据集['Column_Name']。sum()

如果有任何问题,请纠正我。


1

作为其他选择,您可以执行以下操作

Group   Valuation   amount
    0   BKB Tube    156
    1   BKB Tube    143
    2   BKB Tube    67
    3   BAC Tube    176
    4   BAC Tube    39
    5   JDK Tube    75
    6   JDK Tube    35
    7   JDK Tube    155
    8   ETH Tube    38
    9   ETH Tube    56

下面的脚本,您可以用于上面的数据

import pandas as pd    
data = pd.read_csv("daata1.csv")
bytreatment = data.groupby('Group')
bytreatment['amount'].sum()
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.