按多个条件聚合CSV行

时间:2018-02-18 16:23:53

标签: python csv

假设我有一个类似于此文件的CSV文件,只有更大的文件:

Cost center number,Month,Amount 1,Amount 2
1234,1,755,9356
1234,2,6758,786654
1234,1,-954,31234
1234,2,2345,778
1234,5,680,986
5678,6,876,456
5678,6,1426,321
5678,5,823,164
5678,7,4387,3485
91011,11,1582,714
91011,12,778,963
91011,10,28,852
91011,12,23475,147

我想模仿Excel数据透视表功能,并按成本中心,月份和两个金额的总和对数据进行分组,因此输出如下所示:

Cost center number,Month,Amount 1 + Amount 2
1234,1,Amount 1 value + Amount 2 value
1234,2,Amount 1 value + Amount 2 value
1234,5,Amount 1 value + Amount 2 value
5678,6,Amount 1 value + Amount 2 value
5678,5,Amount 1 value + Amount 2 value
5678,7,Amount 1 value + Amount 2 value
91011,11,Amount 1 value + Amount 2 value
91011,10,Amount 1 value + Amount 2 value
91011,12,Amount 1 value + Amount 2 value

到目前为止,我已经尝试遍历每一行并为我感兴趣的数据创建列表,我不知道从那里去哪里:

import csv

filename = 'APAC.csv'

with open(filename) as f:
    reader = csv.reader(f)
    headers = next(reader)     

    for header in enumerate(headers):
        print(header)

    cost_centers = []
    months = []
    amounts1 = []
    amounts2 = []

    for row in reader:
        cost_centers.append(row[1])
        months.append(row[2)]
        amounts1.append(row[3])
        amounts2.append(row[4])

我知道Pandas有'group by'和'agg'的选项,但这对我来说是列表和词典的练习(不过我对不同的方法持开放态度),我宁愿留在本土Python库。

3 个答案:

答案 0 :(得分:2)

使用groupby汇总sum,然后如果需要汇总所有列,请sum添加axis=1

#create DataFrame
df = pd.read_csv('APAC.csv')

df = df.groupby(['Cost center number','Month']).sum().sum(axis=1).reset_index(name='sum')
print (df)

   Cost center number  Month     sum
0                1234      1   40391
1                1234      2  796535
2                1234      5    1666
3                5678      5     987
4                5678      6    3079
5                5678      7    7872
6               91011     10     880
7               91011     11    2296
8               91011     12   25363

<强>详细

print (df.groupby(['Cost center number','Month']).sum())
                          Amount 1  Amount 2
Cost center number Month                    
1234               1          -199     40590
                   2          9103    787432
                   5           680       986
5678               5           823       164
                   6          2302       777
                   7          4387      3485
91011              10           28       852
                   11         1582       714
                   12        24253      1110

如果想要一个班轮首先回答add,那么groupby按列和最后汇总sum

df = (
      df['Amount 1'].add(df['Amount 2'])
                    .groupby([df['Cost center number'], df['Month']])
                    .sum()
                    .reset_index(name='sum')
     )
print (df)
   Cost center number  Month     sum
0                1234      1   40391
1                1234      2  796535
2                1234      5    1666
3                5678      5     987
4                5678      6    3079
5                5678      7    7872
6               91011     10     880
7               91011     11    2296
8               91011     12   25363

答案 1 :(得分:1)

这可以使用Python内置的defaultdict来完成,以帮助为每个cost centermonth创建一个字典条目:

from collections import defaultdict
import csv

filename = 'APAC.csv'
totals = defaultdict(lambda : defaultdict(int))

with open(filename, 'r', newline='') as f_input:
    csv_input = csv.reader(f_input)
    header = next(csv_input)     

    for cost_center, month, amount_1, amount_2 in csv_input:
        totals[cost_center][month] += int(amount_1) + int(amount_2)

with open('output.csv', 'w', newline='') as f_output:        
    csv_output = csv.writer(f_output)
    csv_output.writerow(['Cost center number', 'Month', 'Amount 1 + Amount 2'])

    for cost_center, month_data in sorted(totals.items()):
        for month, total in sorted(month_data.items()):
            csv_output.writerow([cost_center, month, total])

哪个会给你一个output.csv文件,其中包含:

Cost center number,Month,Amount 1 + Amount 2
1234,1,40391
1234,2,796535
1234,5,1666
5678,5,987
5678,6,3079
5678,7,7872
91011,10,880
91011,11,2296
91011,12,25363

通过使用defaultdict,可以更轻松地添加条目,而无需先测试是否已存在。

答案 2 :(得分:0)

这是一种方式。

(1)创建“金额总计”列 (2)按“成本中心编号”和“月份”分组,总计“金额总计”。

df['Amount Total'] = df['Amount 1'] + df['Amount 2']

df.groupby(['Cost center number', 'month'])['Amount Total'].sum().reset_index()

#    Cost center number  month  Amount Total
# 0                1234      1         40391
# 1                1234      2        796535
# 2                1234      5          1666
# 3                5678      5           987
# 4                5678      6          3079
# 5                5678      7          7872
# 6               91011     10           880
# 7               91011     11          2296
# 8               91011     12         25363

对于单行(但不太明确)的答案,请参阅@jezrael's solution