gpt4 book ai didi

pandas - 在 datetimeindex 数据框中选择具有指定日期的行 - Pandas

转载 作者:行者123 更新时间:2023-12-01 14:31:05 25 4
gpt4 key购买 nike

我有一个带有日期时间索引的数据框。我只需要索引属于列表中指定日期的那些行,例如[1,2] 表示星期一和星期二。这在 pandas 中可以用一行代码实现吗?

最佳答案

IIUC 然后以下应该工作:

df[df.index.to_series().dt.dayofweek.isin([0,1])]

例子:

In [9]:
df = pd.DataFrame(index=pd.date_range(start=dt.datetime(2015,1,1), end = dt.datetime(2015,2,1)))
df[df.index.to_series().dt.dayofweek.isin([0,1])]

Out[9]:
Empty DataFrame
Columns: []
Index: [2015-01-05 00:00:00, 2015-01-06 00:00:00, 2015-01-12 00:00:00, 2015-01-13 00:00:00, 2015-01-19 00:00:00, 2015-01-20 00:00:00, 2015-01-26 00:00:00, 2015-01-27 00:00:00]

所以这会将 DateTimeIndex 转换为 Series这样我们就可以调用isin使用 .dt.dayofweek 测试成员资格并传递 0,1(这对应于星期一和星期二),我们使用 bool 掩码来掩码索引

另一种方法是在不转换为 Series 的情况下构造 bool 掩码:

In [12]:
df[(df.index.dayofweek == 0) | (df.index.dayofweek == 1)]

Out[12]:
Empty DataFrame
Columns: []
Index: [2015-01-05 00:00:00, 2015-01-06 00:00:00, 2015-01-12 00:00:00, 2015-01-13 00:00:00, 2015-01-19 00:00:00, 2015-01-20 00:00:00, 2015-01-26 00:00:00, 2015-01-27 00:00:00]

或者实际上这会起作用:

In [13]:
df[df.index.dayofweek < 2]

Out[13]:
Empty DataFrame
Columns: []
Index: [2015-01-05 00:00:00, 2015-01-06 00:00:00, 2015-01-12 00:00:00, 2015-01-13 00:00:00, 2015-01-19 00:00:00, 2015-01-20 00:00:00, 2015-01-26 00:00:00, 2015-01-27 00:00:00]

时间

In [14]:
%timeit df[df.index.dayofweek < 2]
%timeit df[np.in1d(df.index.dayofweek, [1, 2])]

1000 loops, best of 3: 464 µs per loop
1000 loops, best of 3: 521 µs per loop

所以我最后的方法在这里比np方法稍微快一些

关于pandas - 在 datetimeindex 数据框中选择具有指定日期的行 - Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33879197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com