gpt4 book ai didi

python - 在 Pandas 中重采样时的时间增量平均值

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

给定这个数据框:

df = pd.DataFrame(pd.to_timedelta(['00:00:02','00:00:05','00:00:10','00:00:15','00:00:05']))
df.index = pd.to_datetime(['20/02/2017 12:42:10','20/02/2017 12:43:10','20/02/2017 12:45:10','20/02/2017 12:45:10','20/02/2017 12:45:10'])
df.columns = ['time']

df
Out[232]:
time
2017-02-20 12:42:10 00:00:02
2017-02-20 12:43:10 00:00:05
2017-02-20 12:45:10 00:00:10
2017-02-20 12:45:10 00:00:15
2017-02-20 12:45:10 00:00:05

我尝试重新采样,获取每分钟的平均时间。P.e 它在对他们进行总结时起作用:

df.resample('min').sum()
Out[245]:
time
2017-02-20 12:42:00 00:00:02
2017-02-20 12:43:00 00:00:05
2017-02-20 12:44:00 00:00:00
2017-02-20 12:45:00 00:00:30

有什么方法可以使这项工作变得有意义吗?

类似于:

df.resample('min').mean()

最佳答案

您可以先将 timedeltas 转换为 total_seconds ( float ),resample 并使用 fillna .上次转换 to_timedelta返回:

df = pd.to_timedelta(df.time.dt.total_seconds().resample('min').mean().fillna(0), unit='s')
print (df)
2017-02-20 12:42:00 00:00:02
2017-02-20 12:43:00 00:00:05
2017-02-20 12:44:00 00:00:00
2017-02-20 12:45:00 00:00:10
Freq: T, Name: time, dtype: timedelta64[ns]

通过转换为纳秒可以提高精度:

print (pd.Series(df.time.values.astype(np.int64), index=df.index))
2017-02-20 12:42:10 2000000000
2017-02-20 12:43:10 5000000000
2017-02-20 12:45:10 10000000000
2017-02-20 12:45:10 15000000000
2017-02-20 12:45:10 5000000000
dtype: int64

df = pd.to_timedelta(pd.Series(df.time.values.astype(np.int64), index=df.index)
.resample('min').mean().fillna(0))
print (df)
2017-02-20 12:42:00 00:00:02
2017-02-20 12:43:00 00:00:05
2017-02-20 12:44:00 00:00:00
2017-02-20 12:45:00 00:00:10
Freq: T, dtype: timedelta64[ns]

关于python - 在 Pandas 中重采样时的时间增量平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43115442/

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