将此example用于CSV dictreader,如何将特定列和/或不同的顺序输出到CSV?
import csv
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
rows = [{'Symbol':'AA', 'Price':39.48, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.18, 'Volume':181800},
{'Symbol':'AIG', 'Price': 71.38, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.15, 'Volume': 195500},
{'Symbol':'AXP', 'Price': 62.58, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.46, 'Volume': 935000},
]
with open('stocks.csv','w') as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writeheader()
f_csv.writerows(rows)
我如何输出音量,然后输出日期(列重新排序,2列未输出)?
答案 0 :(得分:2)
将extrasaction
参数用于np.maximum
:
with open('stocks.csv','w') as f:
f_csv = csv.DictWriter(f, ['Volume','Date'], extrasaction='ignore')
f_csv.writeheader()
f_csv.writerows(rows)
结果:
Volume,Date
181800,6/11/2007
195500,6/11/2007
935000,6/11/2007
答案 1 :(得分:-1)
我对dictwriter并不是很熟悉,但你可以用你想要的字段建立一个字典列表
myfields = ['Volume', 'Date']
myrows = []
for row in rows:
myrow = {}
for field in myfields:
myrow[field] = row.get(field)
myrows.append(myrow)
f_csv = csv.DictWriter(f, myfields)
f_csv.writeheader()
f_csv.writerows(myrows)