python - 如何根据索引在日期间隔之间的条件过滤数据框?

标签 python pandas dataframe filter time-series

我有 2 个数据框: df_dec_light 和 df_rally。

df_dec_light.head():
    log_return  month   year
1970-12-01  0.003092    12  1970
1970-12-02  0.011481    12  1970
1970-12-03  0.004736    12  1970
1970-12-04  0.006279    12  1970
1970-12-07  0.005351    12  1970
1970-12-08  -0.005239   12  1970
1970-12-09  0.000782    12  1970
1970-12-10  0.004235    12  1970
1970-12-11  0.003774    12  1970
1970-12-14  -0.005109   12  1970
df_rally.head():

rally_start rally_end
0   1970-12-18  1970-12-31
1   1971-12-17  1971-12-31
2   1972-12-15  1972-12-29
3   1973-12-21  1973-12-31
4   1974-12-20  1974-12-31

我需要根据 df_dec_light.index 位于列 df_rally['rally_start'] 和 df_rally['rally_end'] 的值之间的条件来过滤 df_dec_light。

我尝试过这样的事情: df_dec_light[(df_dec_light.index >= df_rally['rally_start']) & (df_dec_light.index <= df_rally['rally_end'])]

我期望收到过滤后的 df_dec_light 数据帧,其索引在 df_rally['rally_start'] 和 df_rally['rally_end'] 之间的间隔内。 像这样的事情:


    log_return  month   year
1970-12-18  0.001997    12  1970
1970-12-21  -0.003108   12  1970
1970-12-22  0.001111    12  1970
1970-12-23  0.000666    12  1970
1970-12-24  0.005644    12  1970
1970-12-28  0.005283    12  1970
1970-12-29  0.010810    12  1970
1970-12-30  0.002061    12  1970
1970-12-31  -0.001301   12  1970

非常感谢任何帮助。谢谢!

最佳答案

让我们根据 df_rally 数据帧中的开始列和结束列值创建一个 IntervalIndex,然后将间隔映射df_dec_light 的索引上dataframe 并使用 notna 检查索引值是否包含在任何区间

ix = pd.IntervalIndex.from_arrays(df_rally.rally_start, df_rally.rally_end, closed='both')
mask = df_dec_light.index.map(ix.to_series()).notna()

然后使用掩码来过滤数据帧

df_dec_light[mask]

关于python - 如何根据索引在日期间隔之间的条件过滤数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74833975/

相关文章:

r - 从计数列创建饼图,并以百分比作为标签

python - Pandas - 有效的方法吗?

python - 如何在div标签下获得没有类的li

python - 如何从 python 理解 HDB 中返回的游标描述列

python - 删除 Pandas 中的第 n 行

python - pandas - 将列转换为分钟值

python - Pyspark 以周格式显示日期值以及周开始日期和结束日期

python - 我们必须在 PySpark 中进行复杂查询还是使用 .filter/.select 进行简单查询?

python - 带有 ISelectionFilter 的 PickObjects 不允许我选择任何内容,为什么?

python - 使用条件更改列值或附加新行的数据框更新 SQLite DB