python - 将 Pandas 时间序列转换为时间增量

标签 python pandas timedelta

我正在尝试绘制 pandas 时间序列,但我希望将自时间序列开始以来的时间作为 X 轴,而不是 y 轴上的实际时间。

是否有任何方便的方法来格式化它或将我的时间序列转换为时间增量序列?

最佳答案

通过索引减去DatetimeIndex第一个值:

s = pd.Series([1,8,9], index= pd.date_range('2015-01-01', periods=3, freq='H'))
print (s)
2015-01-01 00:00:00    1
2015-01-01 01:00:00    8
2015-01-01 02:00:00    9
Freq: H, dtype: int64

s.index = (s.index - s.index[0])
print (s)
00:00:00    1
01:00:00    8
02:00:00    9
dtype: int64

如有必要,将 TimedeltaIndex 转换为秒,使用 total_secondsdays如果 DatetimeIndex 中没有时间:

s.index = (s.index - s.index[0]).total_seconds()
print (s)
0.0       1
3600.0    8
7200.0    9
dtype: int64

关于python - 将 Pandas 时间序列转换为时间增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54807517/

相关文章:

python - Pandas - 在两列中查找具有匹配值的行并在另一列中乘以值

python pandas获取列值的第一位数字

python - 来自锯齿状数组的数据帧

python - 将 int64 转换为日期时间,格式为 %H :%M'

python - 删除 timedelta 对象中的天数

python - 将数据帧与单个值进行比较时如何获取返回的模式

python - 编写带有身份验证的 Python 邮件服务器

Python:在特殊环境中执行代码对象

python - Scapy 模块阻止 PyCharm 调试器

python - 当 timedelta.days 小于 1 时,在 python 中确定 "days"