gpt4 book ai didi

python - 当询问 Timestamp 列值是否具有 attr astype 时,Pandas 给出了错误的结果

转载 作者:行者123 更新时间:2023-12-01 05:00:24 24 4
gpt4 key购买 nike

对于包含 Timestamp 值的列,我得到的关于元素是否具有属性 astype 的结果不一致:

In [30]: o.head().datetime.map(lambda x: hasattr(x, 'astype'))
Out[30]:
0 False
1 False
2 False
3 False
4 False
Name: datetime, dtype: bool

In [31]: map(lambda x: hasattr(x, 'astype'), o.head().datetime.values)
Out[31]: [True, True, True, True, True]

In [32]: o.datetime.dtype
Out[32]: dtype('<M8[ns]')

In [33]: o.datetime.head()
Out[33]:
0 2012-09-30 22:00:15.003000
1 2012-09-30 22:00:16.203000
2 2012-09-30 22:00:18.302000
3 2012-09-30 22:03:37.304000
4 2012-09-30 22:05:17.103000
Name: datetime, dtype: datetime64[ns]

如果我选取第一个元素(或任何单个元素)并询问它是否具有 attr astype,我会发现它具有,而且我什至可以转换为其他格式。

但是,如果我使用 Series.map 一次性对整个列执行此操作,则会收到一条错误消息,声称 Timestamp 对象没有该属性astype(尽管他们显然是这样做的)。

如何使用 Pandas 实现将操作映射到列?这是一个已知错误吗?

版本:pandas 0.13.0,numpy 1.8

已添加

这似乎是 pandas 或 numpy 的某种隐式转换:

In [50]: hasattr(o.head().datetime[0], 'astype')
Out[50]: False

In [51]: hasattr(o.head().datetime.values[0], 'astype')
Out[51]: True

最佳答案

时间戳没有 astype 方法。但 numpy.datetime64 可以。

NDFrame.values returns a numpy array.o.head().datetime.values 返回 dtype numpy.datetime64 的 numpy 数组,这就是原因

In [31]: map(lambda x: hasattr(x, 'astype'), o.head().datetime.values)
Out[31]: [True, True, True, True, True]
<小时/>

请注意,Series.__iter__defined this way :

def __iter__(self):
if com.is_categorical_dtype(self.dtype):
return iter(self.values)
elif np.issubdtype(self.dtype, np.datetime64):
return (lib.Timestamp(x) for x in self.values)
elif np.issubdtype(self.dtype, np.timedelta64):
return (lib.Timedelta(x) for x in self.values)
else:
return iter(self.values)

因此,当 Series 的 dtype 为 np.datetime64 时,对 Series 进行迭代返回时间戳。这就是隐式转换发生的地方。

关于python - 当询问 Timestamp 列值是否具有 attr astype 时,Pandas 给出了错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26350364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com