gpt4 book ai didi

python - 选择每个日期的最后一个时间戳

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:12 24 4
gpt4 key购买 nike

数据框每天只包含几个时间戳,我需要为每个日期选择最新的一个(不是值,时间戳本身)。 df 看起来像这样:

                               A      B      C
2016-12-05 12:00:00+00:00 126.0 15.0 38.54
2016-12-05 16:00:00+00:00 131.0 20.0 42.33
2016-12-14 05:00:00+00:00 129.0 18.0 43.24
2016-12-15 03:00:00+00:00 117.0 22.0 33.70
2016-12-15 04:00:00+00:00 140.0 23.0 34.81
2016-12-16 03:00:00+00:00 120.0 21.0 32.24
2016-12-16 04:00:00+00:00 142.0 22.0 35.20

我通过定义以下函数设法实现了我所需要的:

def find_last_h(df,column):
newindex = []
df2 = df.resample('d').last().dropna()
for x in df2[column].values:
newindex.append(df[df[column]==x].index.values[0])
return pd.DatetimeIndex(newindex)

我用它指定将哪个列的值用作过滤器以获取所需的时间戳。这里的问题是在非唯一值的情况下,这可能无法按预期工作。

另一种使用方式是:

  grouped = df.groupby([df.index.day,df.index.hour])
grouped.groupby(level=0).last()

然后重建时间戳,但它更加冗长。聪明的方法是什么?

最佳答案

使用boolean indexing带有由 duplicated 创建的掩码和 floor截断:

idx = df.index.floor('D')
df = df[~idx.duplicated(keep='last') | ~idx.duplicated(keep=False)]
print (df)
A B C
2016-12-05 16:00:00 131.0 20.0 42.33
2016-12-14 05:00:00 129.0 18.0 43.24
2016-12-15 04:00:00 140.0 23.0 34.81
2016-12-16 04:00:00 142.0 22.0 35.20

另一种解决方案 reset_index + set_index :

df = df.reset_index().groupby([df.index.date]).last().set_index('index')
print (df)
A B C
index
2016-12-05 16:00:00 131.0 20.0 42.33
2016-12-14 05:00:00 129.0 18.0 43.24
2016-12-15 04:00:00 140.0 23.0 34.81
2016-12-16 04:00:00 142.0 22.0 35.20

resamplegroupby dates 仅丢失时间:

print (df.resample('1D').last().dropna())
A B C
2016-12-05 131.0 20.0 42.33
2016-12-14 129.0 18.0 43.24
2016-12-15 140.0 23.0 34.81
2016-12-16 142.0 22.0 35.20

print (df.groupby([df.index.date]).last())
A B C
2016-12-05 131.0 20.0 42.33
2016-12-14 129.0 18.0 43.24
2016-12-15 140.0 23.0 34.81
2016-12-16 142.0 22.0 35.20

关于python - 选择每个日期的最后一个时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44569589/

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