gpt4 book ai didi

python - 如何在分钟内转换(可能为负)Pandas TimeDelta( float )?

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

我有这样一个数据框

df[['timestamp_utc','minute_ts','delta']].head()
Out[47]:
timestamp_utc minute_ts delta
0 2015-05-21 14:06:33.414 2015-05-21 12:06:00 -1 days +21:59:26.586000
1 2015-05-21 14:06:33.414 2015-05-21 12:07:00 -1 days +22:00:26.586000
2 2015-05-21 14:06:33.414 2015-05-21 12:08:00 -1 days +22:01:26.586000
3 2015-05-21 14:06:33.414 2015-05-21 12:09:00 -1 days +22:02:26.586000
4 2015-05-21 14:06:33.414 2015-05-21 12:10:00 -1 days +22:03:26.586000

其中 df['delta']=df.minute_ts-df.timestamp_utc

timestamp_utc     datetime64[ns]
minute_ts datetime64[ns]
delta timedelta64[ns]

问题是,我想获取 timestamp_utcminutes_ts 之间的分钟数(可能为负数),忽略秒部分。

所以对于第一行,我想得到 -120。实际上,2015-05-21 12:06:002015-05-21 14:06:33.414 早 120 分钟。

最 Pandas 式的做法是什么?

非常感谢!

最佳答案

您可以使用:

df['a'] = df['delta'] / np.timedelta64(1, 'm')
print (df)
timestamp_utc minute_ts delta \
0 2015-05-21 14:06:33.414 2015-05-21 12:06:00 -1 days +21:59:26.586000
1 2015-05-21 14:06:33.414 2015-05-21 12:07:00 -1 days +22:00:26.586000
2 2015-05-21 14:06:33.414 2015-05-21 12:08:00 -1 days +22:01:26.586000
3 2015-05-21 14:06:33.414 2015-05-21 12:09:00 -1 days +22:02:26.586000
4 2015-05-21 14:06:33.414 2015-05-21 12:10:00 -1 days +22:03:26.586000

a
0 -120.5569
1 -119.5569
2 -118.5569
3 -117.5569
4 -116.5569

然后将float转换为int:

df['a'] = (df['delta'] / np.timedelta64(1, 'm')).astype(int)
print (df)
timestamp_utc minute_ts delta a
0 2015-05-21 14:06:33.414 2015-05-21 12:06:00 -1 days +21:59:26.586000 -120
1 2015-05-21 14:06:33.414 2015-05-21 12:07:00 -1 days +22:00:26.586000 -119
2 2015-05-21 14:06:33.414 2015-05-21 12:08:00 -1 days +22:01:26.586000 -118
3 2015-05-21 14:06:33.414 2015-05-21 12:09:00 -1 days +22:02:26.586000 -117
4 2015-05-21 14:06:33.414 2015-05-21 12:10:00 -1 days +22:03:26.586000 -116

关于python - 如何在分钟内转换(可能为负)Pandas TimeDelta( float )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38854582/

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