我有一个python列表如下:
[(numpy.datetime64('2000-04-01'), 'pie'),
(numpy.datetime64('2000-04-01'), 'apple'),
(numpy.datetime64('2000-04-01'), 'orange'),
(numpy.datetime64('2000-04-01'), 'mango'),
(numpy.datetime64('2000-04-01'), 'pears')]
我希望它能成为csv文件输出,如下所示
| date | item |
+------------+-------+
| 2000-04-01 | pie |
| 2000-04-01 | apple |
| ... | ... |
答案 0 :(得分:1)
我最终能够输出为csv文件。
import csv
with open('date_prop.csv','w',newline='') as out:
csv_out=csv.writer(out)
csv_out.writerow(['date','item'])
for row in f2:
csv_out.writerow(row)
答案 1 :(得分:1)
直接Python文件写:
In [116]: with open('test','w') as f:
...: print(' date item', file=f)
...: for t in alist:
...: print('%s %s'%t, file=f)
...:
In [117]: cat test
date item
2000-04-01 pie
2000-04-01 apple
2000-04-01 orange
2000-04-01 mango
2000-04-01 pears
关键是str(np.datetime64('2000-04-01')
的格式符合您的要求。
对象dtype数组可以用savetxt
和fmt
编写:
In [121]: arr = np.array(alist)
In [122]: arr
Out[122]:
array([[numpy.datetime64('2000-04-01'), 'pie'],
[numpy.datetime64('2000-04-01'), 'apple'],
[numpy.datetime64('2000-04-01'), 'orange'],
[numpy.datetime64('2000-04-01'), 'mango'],
[numpy.datetime64('2000-04-01'), 'pears']], dtype=object)
In [123]: np.savetxt('test', arr, fmt='%s', delimiter=',', header='date item')
In [124]: cat test
# date item
2000-04-01,pie
2000-04-01,apple
2000-04-01,orange
2000-04-01,mango
2000-04-01,pears
我还可以创建一个结构化数组,并用savetxt
In [125]: arr = np.array(alist, dtype='datetime64[D], U10')
In [126]: arr
Out[126]:
array([('2000-04-01', 'pie'), ('2000-04-01', 'apple'),
('2000-04-01', 'orange'), ('2000-04-01', 'mango'),
('2000-04-01', 'pears')], dtype=[('f0', '<M8[D]'), ('f1', '<U10')])
In [127]: np.savetxt('test', arr, fmt='%s', delimiter=', ', header='date item
...: ')
In [128]: cat test
# date item
2000-04-01, pie
2000-04-01, apple
2000-04-01, orange
2000-04-01, mango
2000-04-01, pears