gpt4 book ai didi

python - 多索引数据框中的 Pandas 切片行失败

转载 作者:行者123 更新时间:2023-12-04 15:03:58 24 4
gpt4 key购买 nike

我有以下数据框,其中日期、小时和代码是多重索引:

                                    1         2         3         4       
date hour code
2020-11-01 13 A1 2.3 2.6 7.4 5.3
2020-11-01 13 A2 7.5 7.8 7.6 7.7
2020-11-01 13 A3 4.2 5.3 5.9 6.1
2020-11-02 11 A1 4.3 3.3 9.8 8.5
2020-11-02 11 A2 4.4 8.6 11.1 4.3
2020-11-02 11 A3 4.3 2.1 4.5 3.8
2020-11-02 12 A1 5.4 5.6 5.8 5.7
...

例如,我正在尝试对数据帧进行切片以仅获取 2020 年 11 月 2 日的 11 点,但我没有这样做。我已尝试按照 here 所述进行操作:

df.loc[(slice(None), slice('2020-11-02',11)), :]

>>>

但返回空数据框(日期是对象,小时是整数)。我也试过:

agg.loc[(slice('2020-11-01'), slice(13)), :]

但是返回错误:

TypeError: '<' not supported between instances of 'datetime.date' and'str'

this帖子我看到我至少可以选择这样的日期:

df.loc[['2020-11-02']]

但这也会返回错误:

KeyError: "['2020-11-01'] not in index"(thought as I mentioned, the date is object)

我的最终目标是能够为每个日期和小时绘制不同的“代码”(例如 1/11/2020 13:00 将包含三行,列值为 1,2,3,4 等)目前我陷入了能够切片 multindex 数据帧的部分。

我的目标是能够根据日期和小时索引对我想要的行进行切片。

编辑:索引数据类型是对象:

agg.index.get_level_values(0).dtype
>>>dtype('O')

最佳答案

您只是遇到了 dtyping 问题:您应该更改列 date 的类型。

如您的错误所述,您的列是包含 datetime.date 对象的 dtype object

首先将其转换为 dtype datetime 的列,它们更易于使用,甚至允许字符串过滤日期!从 datetime.date 对象,它很简单:

df['date'] = pd.to_datetime(df['date'])

然后使用直接索引,它会直接工作:

df.loc['2020-11-02', 11]

然后,如果你想有更多的自由,使用 pd.IndexSlice :

# All A1
df.loc[pd.IndexSlice[:, :, 'A1']]
# All A1 keeping a triple index :
df.loc[pd.IndexSlice[:, :, 'A1':'A1']]
# All 13 o'clock (keeping a triple index) :
df.loc[pd.IndexSlice[:, 13:13, :]]

关于python - 多索引数据框中的 Pandas 切片行失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66493920/

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