我有一个像这样的数据框:
df = pd.DataFrame({"DateTime":["2020-04-02 06:06:22",
"2020-04-02 06:12:22",
"2020-04-02 06:14:39",
"2020-04-02 06:16:56",
"2020-04-02 06:20:34",
"2020-04-02 06:35:44"],
"Data":[23, 31, 10, 23, 56, 81]})
# column DateTime type must be datetime64[ns]
df["DateTime"] = df["DateTime"].astype("datetime64[ns]")
df
Out[4]:
DateTime Data
0 2020-04-02 06:06:22 23
1 2020-04-02 06:12:22 31
2 2020-04-02 06:14:39 10
3 2020-04-02 06:16:56 23
4 2020-04-02 06:20:34 56
5 2020-04-02 06:35:44 81
我想每 10 分钟后选择一次行。所以我的数据框应该是这样的:
DateTime Data
0 2020-04-02 06:06:22 23
3 2020-04-02 06:16:56 23
5 2020-04-02 06:35:44 81
此解决方案How to drop rows based on datetime (every 15 min)?每 15 分钟删除行,但总是查看下面的行,因此它会删除我不想要的行。实际上我想选择特定时间范围之后的行。
有人可以帮助我吗?
最佳答案
这看起来像是 merge_asof
的工作:
# set up indexer DataFrame
df2 = pd.DataFrame({'idx': pd.date_range(df['DateTime'].min(),
df['DateTime'].max(),
freq='10min')
})
# get first value for each slice of 10 minutes
out = (pd.merge_asof(df2, df, left_on='idx', right_on='DateTime',
direction='forward')
#.drop(columns='idx') # uncomment to remove idx
)
输出:
idx DateTime Data
0 2020-04-02 06:06:22 2020-04-02 06:06:22 23
1 2020-04-02 06:16:22 2020-04-02 06:16:56 23
2 2020-04-02 06:26:22 2020-04-02 06:35:44 81
使用.drop(columns='idx')输出
:
DateTime Data
0 2020-04-02 06:06:22 23
1 2020-04-02 06:16:56 23
2 2020-04-02 06:35:44 81
关于python - 选择具有范围的第一行(每 10 分钟),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73460299/