gpt4 book ai didi

python - 如何将代表天数的单个整数转换为 pandas datetime

转载 作者:太空宇宙 更新时间:2023-11-03 15:55:10 27 4
gpt4 key购买 nike

我有一个数据框,其中有一列 float “时间”,代表从 0 到 8 的天数,还有一列包含其他数据。时间步长不连续。

time_clean = np.arange(0, 8, 0.1)
noise = [random.random()/10 for n in range(len(time_clean))]
time = time_clean + noise

data = [random.random()*100 for n in range(len(time_clean))]

df = pd.DataFrame({"time": time, "data":data})
df.head()

data time
0 89.965240 0.041341
1 95.964621 0.109215
2 70.552763 0.232596
3 74.457244 0.330750
4 13.228426 0.471623

我想每 15 分钟对数据进行一次重新采样和插值,(15/(60*24) 天)。

我认为最有效的方法是使用 pandas 数据帧的 resample 方法,但为了做到这一点,我需要将时间列转换为 timestamp,并使其成为索引。

最有效的方法是什么?是否可以将 int 转换为 datetime

最佳答案

我想你需要先转换列 time to_timedelta然后 sort_valuesresample :

此外,我认为最好的方法是添加一个新行 0,因为它始终从 0 开始重新采样(如果 0 不在 time 列它从最小的 time 值开始)

df.loc[-1] = 0
df.time = pd.to_timedelta(df.time, unit='d')
df = df.sort_values('time').set_index('time').resample('15T').ffill()
print (df.head(20))
data
time
00:00:00 0.000000
00:15:00 0.000000
00:30:00 0.000000
00:45:00 0.000000
01:00:00 0.000000
01:15:00 0.000000
01:30:00 50.869889
01:45:00 50.869889
02:00:00 50.869889
02:15:00 50.869889
02:30:00 50.869889
02:45:00 50.869889
03:00:00 50.869889
03:15:00 8.846017
03:30:00 8.846017
03:45:00 8.846017
04:00:00 8.846017
04:15:00 8.846017
04:30:00 8.846017
04:45:00 8.846017

关于python - 如何将代表天数的单个整数转换为 pandas datetime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43783084/

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