访问时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'>
python :3.6.7.final.0
Pandas :0.25.3
NumPy :1.16.4
最佳答案
找到了解决方法 - 使用 .array
而不是 .values
( docs )
print(type(df['A'].array[0]))
> <class 'pandas._libs.tslibs.timestamps.Timestamp'>
这可以防止转换并使我可以访问我想要使用的对象。
关于python - 为什么在调用 '.values' 时 pd.Timestamp 转换为 np.datetime64 ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58749277/