为什么调用“.values”时 pd.Timestamp 会转换为 np.datetime64?

Voy*_*Voy 6 python datetime timestamp pandas datetime64

访问时DataFrame.values,所有pd.Timestamp对象都转换为np.datetime64对象,为什么?包含对象可以存在,因此我不明白为什么总是会发生这种自动转换np.ndarraypd.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

Voy*_*Voy 6

找到了解决方法 - 使用.array而不是.values文档

print(type(df['A'].array[0]))
> <class 'pandas._libs.tslibs.timestamps.Timestamp'>
Run Code Online (Sandbox Code Playgroud)

这可以防止转换并允许我访问我想要使用的对象。


jor*_*mit 5

背后的整个想法.values是:

返回 DataFrame 的 Numpy 表示形式。[文档]

我发现 apd.Timestamp然后“降级”为dtype原生的a 是合乎逻辑的numpy。如果不这样做,那么这样做的目的是什么.values

如果您确实想保留,pd.Timestamp dtype我建议您使用原始版本Series( df.iloc[0])。我没有看到任何其他方法,因为.values使用np.ndarray根据 Github 上的源进行转换。