python – 对pandas中的datetime索引的算术运算
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 对pandas中的datetime索引的算术运算,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2209字,纯文字阅读大概需要4分钟。
内容图文
![python – 对pandas中的datetime索引的算术运算](/upload/InfoBanner/zyjiaocheng/818/d71c39bed204493498f74713d01bacb6.jpg)
在pandas中,您可以通过基于经典整数位置/行的索引或基于日期时间的索引来访问时间系列的特定位置.可以使用基本算术运算来操纵基于整数的索引,例如,如果我对一个频率为12小时的时间序列有一个integer_index并且我想在此前一天访问该条目,我可以简单地执行integer_index – 2.但是,真实世界数据并不总是完美的,有时行丢失.在这种情况下,此方法失败,并且能够使用基于日期时间的索引和减法(例如,从该索引中的一天)将是有帮助的.我怎样才能做到这一点?
示例脚本:
# generate a sample time series
import pandas as pd
s = pd.Series(["A", "B", "C", "D", "E"], index=pd.date_range("2000-01-01", periods=5, freq="12h"))
print s
2000-01-01 00:00:00 A
2000-01-01 12:00:00 B
2000-01-02 00:00:00 C
2000-01-02 12:00:00 D
2000-01-03 00:00:00 E
Freq: 12H, dtype: object
# these to indices should access the same value ("C")
integer_index = 2
date_index = "2000-01-02 00:00"
print s[integer_index] # prints "C"
print s[date_index] # prints "C"
# I can access the value one day earlier by subtracting 2 from the integer index
print s[integer_index - 2] # prints A
# how can I subtract one day from the date index?
print s[date_index - 1] # raises an error
这个问题的背景可以在我之前提交的一篇文章中找到:
Fill data gaps with average of data from adjacent days
用户JohnE找到了我的问题的解决方法,该问题使用基于整数位置的索引.他通过重新采样时间序列确保我有相同间隔的数据.
解决方法:
您的日期时间索引不是基于字符串,它是一个DatetimeIndex意味着您可以使用datetime对象进行适当的索引,而不是看起来像日期的字符串.
下面的代码将date_index转换为datetime对象,然后使用timedelta(days=1)从它中减去“一天”.
# generate a sample time series
import pandas as pd
from datetime import datetime, timedelta
s = pd.Series(["A", "B", "C", "D", "E"], index=pd.date_range("2000-01-01", periods=5, freq="12h"))
print(s)
# these two indices should access the same value ("C")
integer_index = 2
# Converts the string into a datetime object
date_index = datetime.strptime("2000-01-02 00:00", "%Y-%m-%d %H:%M")
print(date_index) # 2000-01-02 00:00:00
print(s[integer_index]) # prints "C"
print(s[date_index]) # prints "C"
print(s[integer_index - 2]) # prints "A"
one_day = timedelta(days=1)
print(s[date_index - one_day]) # prints "A"
print(date_index - one_day) # 2000-01-01 00:00:00
内容总结
以上是互联网集市为您收集整理的python – 对pandas中的datetime索引的算术运算全部内容,希望文章能够帮你解决python – 对pandas中的datetime索引的算术运算所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。