gpt4 book ai didi

python - 不带 Pandas 的 CSV 分组

转载 作者:太空宇宙 更新时间:2023-11-04 11:16:34 25 4
gpt4 key购买 nike

我想将数据分组到 .csv 文件中。我的数据如下:

code,balance
CN,999.99
CN,1.01
LS,177.77
LS,69.42
LA,200.43
WO,100

我想按代码对项目进行分组,然后总结类似代码的余额。期望的输出是:

code,blance
CN,1001
LS,247.19
...

我最初使用 Pandas 来完成这项任务,但没有可用的包来将该库放在服务器上。

mydata = pd.read_csv('./tmp/temp.csv')
out = mydata.groupby('code').sum()

解决方案最好与 Python 2.6 兼容。如果这是重复的,我深表歉意,其他帖子的分组方式似乎不同。

我也想避免在 -

if code = x
add balance to x_total

-一种方式

我的解决方案:

def groupit():
groups = defaultdict(list)
with open('tmp.csv') as fd:
reader = csv.DictReader(fd)
for row in reader:
groups[row['code']].append(float(row['balance.']))
total={key:sum(groups[key]) for key in groups}
total=str(total)
total=total.replace(' ','')
total=total.replace('{','')
total=total.replace('}','')
total=total.replace("'",'')
total=total.replace(',','\n')
total=total.replace(':',',')

outfile = open('out.csv','w+')
outfile.write('code,balance\n')
outfile.write(total)

最佳答案

python > 2.6:

from collections import defaultdict
import csv

groups = defaultdict(list)
with open('text.txt') as fd:
reader = csv.DictReader(fd)
for row in reader:
groups[row['code']].append(float(row['balance']))

totals = {key: sum(groups[key]) for key in groups}
print(totals)

这个输出:

{'CN': 1001.0, 'LS': 247.19, 'LA': 200.43, 'WO': 100.0}

Python = 2.6:

from collections import defaultdict
import csv

groups = defaultdict(list)
with open('text.txt') as fd:
reader = csv.DictReader(fd)
for row in reader:
groups[row['code']].append(float(row['balance']))

totals = dict((key, sum(groups[key])) for key in groups)
print(totals)

关于python - 不带 Pandas 的 CSV 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56874231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com