在Python中找到一个元素的总和

时间:2019-04-09 05:23:07

标签: python python-3.x

有一个csv,具有9列和150万行。这个问题要求我们计算每个帐户的支出。我能够提取7700个帐号。这是有人问到后的文件示例(由于我没有足够的影响力来发布照片,因此这是一个链接):

sample of the file

我非常困惑,因为表中的交易是针对单个项目的,您需要增加数量和价格相乘的额外步骤。

哦,我们不允许使用pandas。而所有这些都是string数据。

我没有做太多尝试,因为除了获得所有帐户ID的列表之外,我还很困惑。即使那对我来说也是一个挑战,所以我们将不胜感激。以下是我用来获取ID列表的简单代码,我敢肯定我什至不应该为此使用import csv,但是很好。

import csv

f_file = open ('myfile.csv')
csv_f_file = csv.reader(f_file)

account_id = []
for row in csv_f_file:
    account_id.append(row[4])

account_id = set(account_id)
account_id_list = list(account_id)

print(customer_id_list)

结果应如下所示(但可以想象7000次):

account:  SID600   
spending: 87.500

感谢任何可以提供帮助的人!

4 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

import csv


with open ('myfile.csv') as f:
    csv_f_file = csv.reader(f)
    data = list(csv_f_file)
    res = {}
    for row in data:
        res[row[3]] = res.get(row[3], 0.0)
        res[row[3]] += float(row[4]) * float(row[5])
    print(res)

答案 1 :(得分:0)

您可以使用pg_dump --DATABASE_URL_COPIED_IN_STEP_3 > database_dump_fileDictReader使其可读,但是必须具有带标头的CSV。另外,您也可以将结果保存到另一个CSV中以保持持久性。

由于在您输入的内容中,同一帐户的每个条目可能会有不同的产品(例如,对于DictWriter,可能会有SID600chair和其他{{1 }}(价格和数量不同),则需要收集每个帐户列表中的所有支出,然后将其总计。

示例CSV输入:

table

代码:

table

其输出将为:

date,trans,item,account,quantity,price
0409,h65009,chair,SID600,12.5,7
0409,h65009,table,SID600,40,2
0409,h65009,table,SID600,22,10
0409,h65009,chair,SID601,30,11
0409,h65009,table,SID601,30,11
0409,h65009,table,SID602,4,9

答案 2 :(得分:-1)

import csv

f_file = open ('myfile.csv')
csv_f_file = csv.reader(p_supermarket_file)

account_id = []
for row in csv_f_file:
    account_id.append(row[4])

account_id = set(account_id)
account_id_list = list(account_id)
for id in account_id_list:
    for row in csv_f_file:
        if row[3] == id:
            total_amount = row[4] * row[5]
#make a dictionary to store amount and its corresponding is in it.

我还没有测试过,但是据我了解。

答案 3 :(得分:-1)

尝试熊猫。与lamda一起使用groupby方法。 如果您的CSV文件具有逐行功能,请进行转置,然后使用groupby方法。

仅参考熊猫官方文档站点。