Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.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 按多个条件聚合CSV行_Python_Csv - Fatal编程技术网

Python 按多个条件聚合CSV行

Python 按多个条件聚合CSV行,python,csv,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

假设我有一个类似于此的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])
我知道熊猫可以选择“分组方式”和“agg”,但这是列表和字典的练习(不过我对不同的方法持开放态度)对于我和我来说,我更喜欢呆在本地Python库中。

使用并聚合
sum
,然后如果需要对所有列求和,使用
axis=1添加
sum

#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
如果希望先得到一个线性答案,然后按列和最后一个聚合进行分组:

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) 创建“总额”列。
(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

有关一行(但不太明确)的答案,请参见。

这可以使用Python的内置功能来帮助为每个
成本中心和
月份创建字典条目:

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
文件,其中包含:

成本中心编号、月份、金额1+金额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
可以更轻松地添加条目,而无需首先测试条目是否已经存在。

非常感谢jezrael。正如我在问题中所说的,如果可能的话,我更愿意省略Pandas,并通过列表或字典找到解决方案(因此,我从我的帖子中删除了Pandas标签,因为它具有误导性)。你认为这是可以实现的吗?是的,这是可能的,但有点复杂-检查