使用包含日期的多索引过滤 Pandas df,仅包含给定日期之后的行
Filter Pandas df with multi index that includes date to only rows after a given date
我有一个 pandas 每日股票价格的 df,其中包含从 2007 年到现在的数据。 df 具有 Ticker 和 Date 的多重索引。我正在尝试获取一个新的 df,它是该数据的一个子集,它只包含 2021 年以后的数据。
此代码有效,但速度很慢。
# reduce the dataset to just data since start date
start_date = pd.to_datetime("2021-01-01")
new_df = df.iloc[df.index.get_level_values('Date') >= start_date]
我尝试了另一种方法,但它只有 returns 个准确日期的值。如何将其更改为 select 从 2021 年开始的范围?
new_df = df.loc[(slice(None), '2021-01-01'), :]
另一个解决方案是重置索引以将日期放入列中,然后过滤并重新索引,但我认为必须有更简单的方法来执行此操作。
将 loc
与 axis=0
一起使用,因此可以在 2021-01-01
之后指定值:
mux = pd.MultiIndex.from_product([['A', 'B'],
pd.date_range('2020-01-01', freq='6MS', periods=5)])
df = pd.DataFrame({'a': range(10)}, index=mux)
print (df)
a
A 2020-01-01 0
2020-07-01 1
2021-01-01 2
2021-07-01 3
2022-01-01 4
B 2020-01-01 5
2020-07-01 6
2021-01-01 7
2021-07-01 8
2022-01-01 9
new_df = df.loc(axis=0)[:, '2021-01-01':]
print (new_df)
a
A 2021-01-01 2
2021-07-01 3
2022-01-01 4
B 2021-01-01 7
2021-07-01 8
2022-01-01 9
为了提高性能应该稍微改变一下你的解决方案,因为loc
解决方案很慢:
new_df = df[df.index.get_level_values('Date') >= "2021-01-01"]
我有一个 pandas 每日股票价格的 df,其中包含从 2007 年到现在的数据。 df 具有 Ticker 和 Date 的多重索引。我正在尝试获取一个新的 df,它是该数据的一个子集,它只包含 2021 年以后的数据。
此代码有效,但速度很慢。
# reduce the dataset to just data since start date
start_date = pd.to_datetime("2021-01-01")
new_df = df.iloc[df.index.get_level_values('Date') >= start_date]
我尝试了另一种方法,但它只有 returns 个准确日期的值。如何将其更改为 select 从 2021 年开始的范围?
new_df = df.loc[(slice(None), '2021-01-01'), :]
另一个解决方案是重置索引以将日期放入列中,然后过滤并重新索引,但我认为必须有更简单的方法来执行此操作。
将 loc
与 axis=0
一起使用,因此可以在 2021-01-01
之后指定值:
mux = pd.MultiIndex.from_product([['A', 'B'],
pd.date_range('2020-01-01', freq='6MS', periods=5)])
df = pd.DataFrame({'a': range(10)}, index=mux)
print (df)
a
A 2020-01-01 0
2020-07-01 1
2021-01-01 2
2021-07-01 3
2022-01-01 4
B 2020-01-01 5
2020-07-01 6
2021-01-01 7
2021-07-01 8
2022-01-01 9
new_df = df.loc(axis=0)[:, '2021-01-01':]
print (new_df)
a
A 2021-01-01 2
2021-07-01 3
2022-01-01 4
B 2021-01-01 7
2021-07-01 8
2022-01-01 9
为了提高性能应该稍微改变一下你的解决方案,因为loc
解决方案很慢:
new_df = df[df.index.get_level_values('Date') >= "2021-01-01"]