python - 为什么在调用 '.values' 时 pd.Timestamp 转换为 np.datetime64 ?

标签 python pandas datetime timestamp 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'>


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/

相关文章:

python - pip 未安装 Scrapy 命令行工具

python - 如何将 Pandas DataFrame 转换为 Pandas ML ModelFrame?

html - 如何使用 DateTime 对象执行函数?

c# - 与 Linq 的不同日期

python - 我在Open CV中使用TF对象检测API

python - 取消存储在网络驱动器上的大型对象

python - 处理 Pandas 中的重复数据

python - 合并和采样两个 Pandas 时间序列

python - 计算 groupby pandas 中独特组合的平均值

c# - DateTime.TryParseExact 加一分钟?