我有以下内容。 pandas 数据框(带有日期时间索引的 df):
datetime Year cal val
1/1/2000 2000 1 0.23
1/2/2000 2000 1 0.34
2/3/2000 2000 1 0.45
4/4/2000 2000 2 0.56
4/5/2000 2000 2 0.67
4/6/2000 2000 2 0.78
5/7/2000 2000 3 0.89
7/8/2000 2000 3 1
7/9/2000 2000 3 1.11
如何从列表中提取与月份相对应的行:
list_months = [1, 2]
生成的数据框将是:
datetime Year cal val
1/1/2000 2000 1 0.23
1/2/2000 2000 1 0.34
我尝试过这个,但它不起作用:
[x for x in df if df.index.month in list_months]
最佳答案
也许你可以使用index.to_series
和 isin
:
print df[df.index.to_series().dt.month.isin(list_months)]
Year cal val
datetime
2000-01-01 2000 1 0.23
2000-02-01 2000 1 0.34
关于python - 基于月份提取 pandas 数据框的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34987632/