gpt4 book ai didi

python - 在 Python-Pandas 中,如何通过特定的日期时间索引值对数据帧进行子集化?

转载 作者:太空宇宙 更新时间:2023-11-03 11:51:17 26 4
gpt4 key购买 nike

我有一个很多天的数据框,看起来像这样......连续的 30 分钟间隔行:

                      a   b
2006-05-08 09:30:00 10 13
2006-05-08 10:00:00 11 12
.
.
.
2006-05-08 15:30:00 15 14
2006-05-08 16:00:00 16 15

但是,我只关心特定的时间,所以我希望 df 的每一天看起来像:

2006-05-08 09:30:00  10  13
2006-05-08 11:30:00 14 15
2006-05-08 13:00:00 18 15
2006-05-08 16:00:00 16 15

意思是,我只想保留数据框中所有不同日期的行(16、13、11:30、9:30)。

谢谢

更新:

我取得了一些进步,使用

hour = df.index.hour
selector = ((hour == 16) | (hour == 13) | (hour == 11) | (hour == 9))
df = df[selector]

但是,我也需要考虑分钟数,所以我尝试了:

minute = df.index.minute
selector = ((hour == 16) & (minute == 0) | (hour == 3) & (minute == 0) | (hour == 9) & (minute == 30) | (hour == 12) & (minute == 0))

但是我得到错误:

ValueError: operands could not be broadcast together with shapes (96310,) (16500,) 

最佳答案

import numpy as np
import pandas as pd
N = 100
df = pd.DataFrame(range(N), index=pd.date_range('2000-1-1', freq='30T',
periods=N))
mask = np.in1d((df.index.hour)*100+(df.index.minute), [930, 1130, 1300, 1600])
print(df.loc[mask])

产量

                      0
2000-01-01 09:30:00 19
2000-01-01 11:30:00 23
2000-01-01 13:00:00 26
2000-01-01 16:00:00 32
2000-01-02 09:30:00 67
2000-01-02 11:30:00 71
2000-01-02 13:00:00 74
2000-01-02 16:00:00 80

关于python - 在 Python-Pandas 中,如何通过特定的日期时间索引值对数据帧进行子集化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26855638/

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