使用Numpy保存一列日期格式

问题描述 投票:0回答:1

我正在尝试使用以下Python代码保存带有日期列的文本文件。我运行最后一行时遇到以下错误消息:

“是{IndexError}元组索引超出范围”

import numpy as np

dt = np.datetime64('%4d-%02d-%02d' % (2018,2,9))
names = ['date']
formats = ['datetime64[us]']
dtype = dict(names=names, formats=formats)
column = np.array(dt, dtype)
np.savetxt('date_series.csv', column, delimiter=',', header='date')

引用的错误消息是什么索引?如何纠正代码?

date numpy datetime
1个回答
2
投票
In [263]: np.savetxt('test',column)
....
ValueError: Expected 1D or 2D array, got 0D array instead

更改为保存1d数组:

In [264]: np.savetxt('test',[column])
---------------------------------------------------------------------------
...
TypeError: float() argument must be a string or a number, not 'datetime.datetime'


TypeError: Mismatch between array dtype ('[('date', '<M8[us]')]') and format specifier ('%.18e')

使用通用的%s格式:

In [265]: np.savetxt('test',[column], fmt='%s')
In [266]: cat test
2018-02-09T00:00:00.000000

2d阵列次数:

In [271]: times = np.arange(np.datetime64('2018-02-09'),np.datetime64('2018-02-27'))
In [272]: times = times.reshape(3,-1)
In [273]: np.savetxt('test',times, fmt='%s')
In [274]: cat test
2018-02-09 2018-02-10 2018-02-11 2018-02-12 2018-02-13 2018-02-14
2018-02-15 2018-02-16 2018-02-17 2018-02-18 2018-02-19 2018-02-20
2018-02-21 2018-02-22 2018-02-23 2018-02-24 2018-02-25 2018-02-26

1d结构化数组的字段将被视为列:

In [288]: dt=np.dtype('<M8[D],<M8[D],<M8[D]')
In [290]: arr = np.array([tuple(x) for x in times.T.tolist()],dt)
In [291]: np.savetxt('test',arr,fmt='%s')
In [292]: cat test
2018-02-09 2018-02-15 2018-02-21
2018-02-10 2018-02-16 2018-02-22
2018-02-11 2018-02-17 2018-02-23
2018-02-12 2018-02-18 2018-02-24
2018-02-13 2018-02-19 2018-02-25
2018-02-14 2018-02-20 2018-02-26

In [296]: np.savetxt('test',arr,fmt='%s, %10s; %20s')
In [297]: cat test
2018-02-09, 2018-02-15;           2018-02-21
2018-02-10, 2018-02-16;           2018-02-22
...
© www.soinside.com 2019 - 2024. All rights reserved.