简体   繁体   中英

Pandas DataFrame Groupby and Sum Into New DataFrame

I have two columns in a dataframe:

office  cost
ABC 20
XYZ 10
ABC 100
XYZ 50

grouped = df.groupby(['office'])
test = grouped.aggregate(np.sum)

when I load either grouped or test into a csv file, I see only only the sum of costs Is there a way I can load both columns office and sum of cost into a new dataframe and then into csv?

ABC 120
XYZ  60

test.to_csv('/tmp/out') writes

office,cost
ABC,120
XYZ,60

to /tmp/out . This shows both columns, the office and the sum of the cost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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