切片Pandas数据帧非单调索引

问题描述 投票:2回答:1

我正在尝试切片DataFrame以返回时间序列的特定部分。然而,这个时间是由一周给我带来麻烦的。

df
       Week  one  two
0   12/3/2017    0    7
1   12/3/2017    6    1
2  12/10/2017    5    8
3  12/10/2017    2    4
4  12/17/2017    3    7
5  12/17/2017    2    0
6  12/24/2017    8    9

我一直试图通过将'Week'列设置为索引然后使用部分字符串索引进行切片,但我不断收到一个关键错误,说“不能将左边的切片绑定到非唯一标签:'12 / 3/2017'”

df = df.set_index('Week')
df = df['12/3/2017':'12/17/2017']

KeyError: "Cannot get left slice bound for non-unique label: '12/3/2017'"

关于如何使这项工作的任何建议?

python python-3.x dataframe slice
1个回答
1
投票

是的,使用loc

df.loc['12/3/2017':'12/17/2017']

            one  two
Week                
12/3/2017     0    7
12/3/2017     6    1
12/10/2017    5    8
12/10/2017    2    4
12/17/2017    3    7
12/17/2017    2    0

这适用于v0.21

© www.soinside.com 2019 - 2024. All rights reserved.