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

Python 如何通过将一列中的数据添加到一行来生成表?,python,Python,我有一个csv文件,我需要把它做成一个表格 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年等,第二列是每年借记的总额,下一列是这样贷记的总额 Year Total Cre

我有一个csv文件,我需要把它做成一个表格

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年等,第二列是每年借记的总额,下一列是这样贷记的总额

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


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

def get_数据(文件):
数据={}
打开(文件,'r')作为f:
对于f.read().split('\n')中的行:
公司,代理人,年,月,日,值,传输类型=行。替换(“”,“”),拆分(“”,“”)
年份=整数(年)
值=浮动(值)
如果年份不在data.keys()中:data.update({year:{trantype:value}})
elif trantype不在数据[year]中。键():数据[year]。更新({trantype:value})
其他:数据[年份][传输类型]+=值
返回数据
file='tmp.tmp'
数据=获取数据(文件)

fmt_head='{:欢迎使用StackOverflow.,并…在此处应用。一对未经修饰的非现场链接并不构成问题。您以何种格式获取数据?您必须从图像复制数据还是已经在程序中?要写入csv文件,您应该查看
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.)