繁体   English   中英

如何对由另一列分组的列中的值求和

[英]How to sum values in a column grouped by another column

我有这个 CSV 文件:

ID,NAME,CITY,COUNTRY,CPERSON,EMPLCNT,CONTRCNT,CONTRCOST
00000001,Breadpot,Sydney,Australia,Sam.Keng@info.com,250,48,1024.00
00000002,Hoviz,Manchester,UK,harry.ham@hoviz.com,150,7,900.00
00000003,Hoviz,London,UK,hamlet.host@hoviz.com,1500,12800,10510.50
00000004,Grenns,London,UK,grenns@grenns.com,200,12800,128.30
00000005,Magnolia,Chicago,USA,man@info.com,1024,25600,512000.00
00000006,Dozen,San Francisco,USA,dozen@dozen.com,1000,5,1000.20
00000007,Sun,San Francisco,USA,sunny@sun.com,2000,2,10000.01

我要做的是找到 CONTRCNT 数量最多的 COUNTRY。 有些国家在 dataframe 中出现了不止一次,所以我需要找到 CONTRCNT 总和最大的国家。

我考虑过总结所有国家/地区的 CONTRCNT,然后找到最大的一个,但我想以一种不是蛮力的方式做到这一点。 我实际上想知道如何使用 Pandas 的 groupby function 来解决这个问题。

所以你可以用 sum groupby然后做idxmax

df.groupby('COUNTRY')['CONTRCOST'].sum().idxmax()

然后

s = df.groupby('COUNTRY')['CONTRCOST'].sum()
s[s==s.max()]

你可以试试这个

import pandas as pd

df = pd.read_csv("data.csv")
print(df,"\n")

country = df.groupby('COUNTRY')['CONTRCNT'].sum()
country = country[country==country.max()]
print(country,"\n")

# Once groupby is used, the particular columns becomes index, so it can be accessed using below statement
print(country.index.values, "\n")

# Index is used as -1 in case there are multiple data with same value, and data is sorted and we will be needing last data value only
print("Country with the largest number of customers' contracts:", country.index.values[-1], "({} contracts)".format(country[-1]))

这应该给你想要的 output

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM