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

标签 python pandas filter slice multi-index

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

                                    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 等) 目前我陷入了能够对多索引数据帧进行切片的阶段。

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

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

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

最佳答案

您只是遇到了打字问题:您应该更改列的类型日期

如错误中所述,您的列的数据类型为 object,其中包含 datetime.date 对象。

首先将其转换为数据类型日期时间的列,它们更容易使用,甚至允许字符串过滤日期!从 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/

相关文章:

r - Shiny DT 包过滤器警告

svn - 传输 FTP 忽略文件

python - 遍历 numpy 数组的最快方法是什么

python - 使用 KeyboardInterrupt 终止子进程

python - 我需要一个 numpy 数组中的 N 个最小(索引)值

python错误抑制信号18到win32

python - 强制 pandas.to_excel 将数据写入 'Text' 而不是 'General' 格式

python - 优化将列表列拆分为单独的列

html - 背景滤镜超出边界半径

Python 切片和负步幅——为什么这些例子明显矛盾?