gpt4 book ai didi

python - recarray 中的 numpy datetime64

转载 作者:行者123 更新时间:2023-12-01 11:44:31 25 4
gpt4 key购买 nike

我在创建 datetime64 类型的记录数组时遇到问题。我正在运行 Python 2.7、Numpy 1.7。

这是一个最小的例子:

p_dtype = np.dtype({"names": ['trns_id', 'trns_date', 'qty', 'price', 'amount', 'description', 'commission', 'fees'],
"formats": [long, "M8", float, float, float, "S40", float, float]})

p_row = (8609132959, np.datetime64('2012-05-01'), 337.574, 4.86, -1640.61, 'Bought 337.574 XYZ @ 4.86', 0.0, 0.0)

print p_list, p_dtype

p_array = np.array(p_row, dtype=p_dtype)

我收到以下错误(和输出):

TypeError                                 Traceback (most recent call last)
<ipython-input-137-0b4de45b819c> in <module>()
6 print p_list, p_dtype
7
----> 8 p_array = np.array(p_row, dtype=p_dtype)
9
10 print "Array: %s, dtype: %s" % (p_array, p_array.dtype)

TypeError: Cannot cast NumPy timedelta64 scalar from metadata [D] to according to the rule 'same_kind'

(8609132959.0, numpy.datetime64('2012-05-01'), 337.574, 4.86, -1640.61, 'Bought 337.574 PIMSX @ 4.86', 0.0, 0.0) [('trns_id', '<i8'), ('trns_date', '<M8'), ('qty', '<f8'), ('price', '<f8'), ('amount', '<f8'), ('description', 'S40'), ('commission', '<f8'), ('fees', '<f8')]

提示,有人吗?

最佳答案

指定“日期”日期时间数据类型。即 "M8[D]" 而不是 "M8",或者 'datetime64[D]' 而不是 'datetime64 '.

In [80]: np.array([(0,np.datetime64('2012-05-17'))],
....: dtype=[('i',np.int),('date','datetime64[D]')])
Out[80]:
array([(0, datetime.date(2012, 5, 17))],
dtype=[('i', '<i8'), ('date', '<M8[D]')])

请注意,您还可以将数据作为简单的字符串输入(即 '2012-05-17',而不是 np.datetime('2012-05-17') 对象)

In [81]: np.array([(0,'2012-05-17')],
....: dtype=[('i',np.int),('date','datetime64[D]')])
Out[81]:
array([(0, datetime.date(2012, 5, 17))],
dtype=[('i', '<i8'), ('date', '<M8[D]')])

似乎这些类型在单个 dtype 情况下与在结构化 dtype 情况下的解释不同。你不会遇到像这里这样的单一数据类型的问题:

In [84]: np.array([np.datetime64('2012-05-17')], dtype='datetime64')   # no need for [D]
Out[84]: array(['2012-05-17'], dtype='datetime64[D]')

In [85]: np.array(['2012-05-17'], dtype='datetime64') # no need for [D]
Out[85]: array(['2012-05-17'], dtype='datetime64[D]')

但是让它结构化,你确实遇到了问题:

In [87]: np.array([(0,'2012-05-17')],
....: dtype=[('i',np.int),('date','datetime64')])
---------------------------------------------------------------------------
ValueError: Cannot create a NumPy datetime other than NaT with generic units

In [88]: np.array([(0,np.datetime64('2012-05-17'))],
....: dtype=[('i',np.int),('date','datetime64')])
---------------------------------------------------------------------------
TypeError: Cannot cast NumPy timedelta64 scalar from metadata [D] to according to the rule 'same_kind'

关于python - recarray 中的 numpy datetime64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16618499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com