9月25日总结
Series 与 Index 的类型是 ExtensionArray (opens new window)时, to_numpy() (opens new window)会复制数据,并强制转换值。详情见数据类型 (opens new window)。
to_numpy() (opens new window)可以控制 numpy.ndarray (opens new window)生成的数据类型。以带时区的 datetime 为例,NumPy 未提供时区信息的 datetime 数据类型,Pandas 则提供了两种表现形式:
-
一种是带
Timestamp(opens new window)的numpy.ndarray(opens new window),提供了正确的tz信息。 -
另一种是
datetime64[ns],这也是一种numpy.ndarray(opens new window),值被转换为 UTC,但去掉了时区信息。
时区信息可以用 dtype=object 保存。
In [14]: ser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))
In [15]: ser.to_numpy(dtype=object)
Out[15]:
array([Timestamp('2000-01-01 00:00:00+0100', tz='CET', freq='D'),
Timestamp('2000-01-02 00:00:00+0100', tz='CET', freq='D')],
dtype=object)
或用 dtype='datetime64[ns]' 去除。
In [16]: ser.to_numpy(dtype="datetime64[ns]")
Out[16]:
array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00.000000000'],
dtype='datetime64[ns]')
提取 DataFrame 里的原数据稍微有点复杂。DataFrame 里所有列的数据类型都一样时,DataFrame.to_numpy() (opens new window)返回底层数据:
In [17]: df.to_numpy()
Out[17]:
array([[-0.1732, 0.1192, -1.0442],
[-0.8618, -2.1046, -0.4949],
[ 1.0718, 0.7216, -0.7068],
[-1.0396, 0.2719, -0.425 ],
[ 0.567 , 0.2762, -1.0874],
[-0.6737, 0.1136, -1.4784],
[ 0.525 , 0.4047, 0.577 ],
[-1.715 , -1.0393, -0.3706]])

浙公网安备 33010602011771号