gpt4 book ai didi

python - loc 使用 DataFrame 自己的索引在 DataFrame 上失败?

转载 作者:太空宇宙 更新时间:2023-11-04 01:09:51 25 4
gpt4 key购买 nike

我有一个带有 DateTime 索引的 DataFrame,其中有许多重复的索引标签(即具有相同日期时间的行)。我想查看具有相同日期时间的行。所以我有以下内容

utimes = pd.unique(data.index.tolist())
for time in utimes:
data_now = data.loc[time]
# Do some processing on the data_now

失败并出现示例错误:KeyError '标签 [2015-02-05 21:54:00+00:00] 不在 [索引] 中'

只是为了检查这不是创建 utimes 的问题,这失败了

data.loc[data.index[0]]

同样的错误信息。怎么会这样?这是索引的样子

> data.index
<class 'pandas.tseries.index.DatetimeIndex'>
[2015-02-05 21:54:00+00:00, ..., 2015-02-05 23:24:00+00:00]
Length: 457, Freq: None, Timezone: UTC

> data.index[0]
Timestamp('2015-02-05 22:24:00+0000', tz='UTC')

知道为什么我不能将 .loc 与 data_frame 自己的索引一起使用吗?

最佳答案

看起来 pd.unique 不遵守 datetime64 dtype:

In [11]: df.index
Out[11]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2015-02-05 22:24:00+00:00]
Length: 1, Freq: None, Timezone: UTC

In [12]: pd.unique(df.index)
Out[12]: array([1423175040000000000L], dtype=object)

现在(直到这个错误在 pandas 中得到修复)你可以将它包装在 to_datetime 调用中:

In [13]: pd.to_datetime(pd.unique(df.index))
Out[13]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2015-02-05 22:24:00]
Length: 1, Freq: None, Timezone: None

或者,更简洁地,您可以使用独特的方法 DatetimeIndex:

In [14]: df.index.unique()
Out[14]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2015-02-05 22:24:00+00:00]
Length: 1, Freq: None, Timezone: UTC

关于python - loc 使用 DataFrame 自己的索引在 DataFrame 上失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28356501/

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