如何通过将一列中的数据添加到一行中来生成表?

2024-05-16 07:08:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv文件,我需要做一个表

placeholder texter

Electric Ireland, John Smyth, 2017, 05, 12, 11.58, credit
Energia, Missy May, 2016, 12, 22, 122.52, debit
Vodafone, John Smyth, 2016, 11, 17, 20.00, debit

我怎样才能做一个表格,第一列是每年2019年2018年等,第二列是每年借记的总额,下一列是这样贷记的总额

place-holder text

Year     Total Credited    Total Debited
2016     €123.45           €678.90
2017     €543.21           €987.60

Tags: 文件csvjohnmay表格totaldebitcredit
1条回答
网友
1楼 · 发布于 2024-05-16 07:08:50

我建议用一本字典来按年度追踪总数。 如果文件tmp.tmp是您的文件名,那么下面的代码可以工作(假设格式与您提供的示例数据一致)

def get_data(file):
  data={}
  with open(file,'r') as f:
    for line in f.read().split('\n'):
      company,agent,year,month,day,value,trantype=line.replace(' ','').split(',')
      year=int(year)
      value=float(value)
      if year not in data.keys(): data.update({year:{trantype:value}})
      elif trantype not in data[year].keys(): data[year].update({trantype:value})
      else: data[year][trantype]+=value
  return data

file='tmp.tmp'

data=get_data(file)
fmt_head='{:<9s}{:<17s}{:<13s}'
fmt_row='{:<9d}{:<17.2f}{:<13.2f}'

print fmt_head.format('Year','Total Credited','Total Debited')
for year in sorted(data.keys()):
  print fmt_row.format(year,data[year]['credit'] if 'credit' in data[year].keys() else 0.,data[year]['debit'] if 'debit' in data[year].keys() else 0.)

相关问题 更多 >