pandas 为什么我不能使用定义的列表过滤python索引?

nkkqxpd9  于 2023-02-14  发布在  Python
关注(0)|答案(1)|浏览(74)

所以我上了一门Pandas和小傻瓜的课程,遇到了一个问题,课程老师执行了解决方案,它起作用了,我遵循了每一步,它对我不起作用
请原谅篇幅过长,为了清晰起见,我包含了实际数据集
我按照指示将列表中的以下项目分配给变量"dates",请参见下文

dates = [
    "2016-12-22",
    "2017-05-03",
    "2017-01-06",
    "2017-03-05",
    "2017-02-12",
    "2017-03-21",
    "2017-04-14",
    "2017-04-15",
]

那么我有一个系列im,它使用下面的数据对named oil_series进行处理

Date is the Index Name

date

2016-12-20
2016-12-21
2016-12-22
2016-12-23
2016-12-27
2016-12-28
2016-12-29
2016-12-30
2017-01-03
2017-01-04
2017-01-05
2017-01-06
2017-01-09
2017-01-10
2017-01-11
2017-01-12
2017-01-13
2017-01-17
2017-01-18
2017-01-19
2017-01-20
2017-01-23
2017-01-24
2017-01-25
2017-01-26
2017-01-27
2017-01-30
2017-01-31
2017-02-01
2017-02-02
2017-02-03
2017-02-06
2017-02-07
2017-02-08
2017-02-09
2017-02-10
2017-02-13
2017-02-14
2017-02-15
2017-02-16
2017-02-17
2017-02-21
2017-02-22
2017-02-23
2017-02-24
2017-02-27
2017-02-28
2017-03-01
2017-03-02
2017-03-03
2017-03-06
2017-03-07
2017-03-08
2017-03-09
2017-03-10
2017-03-13
2017-03-14
2017-03-15
2017-03-16
2017-03-17
2017-03-20
2017-03-21
2017-03-22
2017-03-23
2017-03-24
2017-03-27
2017-03-28
2017-03-29
2017-03-30
2017-03-31
2017-04-03
2017-04-04
2017-04-05
2017-04-06
2017-04-07
2017-04-10
2017-04-11
2017-04-12
2017-04-13
2017-04-17
2017-04-18
2017-04-19
2017-04-20
2017-04-21
2017-04-24
2017-04-25
2017-04-26
2017-04-27
2017-04-28
2017-05-01
2017-05-02
2017-05-03
2017-05-04
2017-05-05
2017-05-08
2017-05-09
2017-05-10
2017-05-11
2017-05-12
2017-05-15

Values

52.22
51.44
51.98
52.01
52.82
54.01
53.8
53.75
52.36
53.26
53.77
53.98
51.95
50.82
52.19
53.01
52.36
52.45
51.12
51.39
52.33
52.77
52.38
52.14
53.24
53.18
52.63
52.75
53.9
53.55
53.81
53.01
52.19
52.37
52.99
53.84
52.96
53.21
53.11
53.41
53.41
54.02
53.61
54.48
53.99
54.04
54
53.82
52.63
53.33
53.19
52.68
49.83
48.75
48.05
47.95
47.24
48.34
48.3
48.34
47.79
47.02
47.29
47
47.3
47.02
48.36
49.47
50.3
50.54
50.25
50.99
51.14
51.69
52.25
53.06
53.38
53.12
53.19
52.62
52.46
50.49
50.26
49.64
48.9
49.22
49.22
48.96
49.31
48.83
47.65
47.79
45.55
46.23
46.46
45.84
47.28
47.81
47.83
48.86

因此,当我编写下面的代码来根据我创建的"dates"列表过滤索引为日期的"oil_prices"时,请参见下面的代码

mask = (oil_series.index.isin(dates)) & (oil_series <= 50)

oil_series.loc[mask]

将发生以下错误
Error from running the code
请帮助我了解问题

r3i60tvu

r3i60tvu1#

根据您的注解,您只有一个级别的MultiIndex。将其转换为Index,您的代码应该可以正常工作:

oil_series.index = oil_series.index.get_level_values('date')

# Your code here.
mask = (oil_series.index.isin(dates)) & (oil_series <= 50)

相关问题