Voy*_*Voy 6 python datetime timestamp pandas datetime64
访问时DataFrame.values
,所有pd.Timestamp
对象都转换为np.datetime64
对象,为什么?包含对象可以存在,因此我不明白为什么总是会发生这种自动转换np.ndarray
。pd.Timestamp
你知道如何预防吗?
最小的例子:
import numpy as np
import pandas as pd
from datetime import datetime
# Let's declare an array with a datetime.datetime object
values = [datetime.now()]
print(type(values[0]))
> <class 'datetime.datetime'>
# Clearly, the datetime.datetime objects became pd.Timestamp once moved to a pd.DataFrame
df = pd.DataFrame(values, columns=['A'])
print(type(df.iloc[0][0]))
> <class 'pandas._libs.tslibs.timestamps.Timestamp'>
# Just to be sure, lets iterate over each datetime and manually convert them to pd.Timestamp
df['A'].apply(lambda x: pd.Timestamp(x))
print(type(df.iloc[0][0]))
> <class 'pandas._libs.tslibs.timestamps.Timestamp'>
# df.values (or series.values in this case) returns an np.ndarray
print(type(df.iloc[0].values))
> <class 'numpy.ndarray'>
# When we check what is the type of elements of the '.values' array,
# it turns out the pd.Timestamp objects got converted to np.datetime64
print(type(df.iloc[0].values[0]))
> <class 'numpy.datetime64'>
# Just to double check, can an np.ndarray contain pd.Timestamps?
timestamp = pd.Timestamp(datetime.now())
timestamps = np.array([timestamp])
print(type(timestamps))
> <class 'numpy.ndarray'>
# Seems like it does. Why the above conversion then?
print(type(timestamps[0]))
> <class 'pandas._libs.tslibs.timestamps.Timestamp'>
Run Code Online (Sandbox Code Playgroud)
蟒蛇:3.6.7.final.0
熊猫:0.25.3
numpy:1.16.4
找到了解决方法 - 使用.array
而不是.values
(文档)
print(type(df['A'].array[0]))
> <class 'pandas._libs.tslibs.timestamps.Timestamp'>
Run Code Online (Sandbox Code Playgroud)
这可以防止转换并允许我访问我想要使用的对象。
背后的整个想法.values
是:
返回 DataFrame 的 Numpy 表示形式。[文档]
我发现 apd.Timestamp
然后“降级”为dtype
原生的a 是合乎逻辑的numpy
。如果不这样做,那么这样做的目的是什么.values
?
如果您确实想保留,pd.Timestamp
dtype
我建议您使用原始版本Series
( df.iloc[0]
)。我没有看到任何其他方法,因为.values
使用np.ndarray
根据 Github 上的源进行转换。
归档时间: |
|
查看次数: |
1316 次 |
最近记录: |