Python 如何从对象类型为 datetime.time 的 Pandas DataFrame.Index 添加/减去时间(小时、分钟等)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28954093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?
提问by Cameron Stark
I've got a DataFrame who's index is just datetime.time and there's no method in DataFrame.Index and datetime.time to shift the time. datetime.time has replace but that'll only work on individual items of the Series?
我有一个 DataFrame 的索引只是 datetime.time 并且 DataFrame.Index 和 datetime.time 中没有方法来改变时间。datetime.time 已替换但仅适用于系列的单个项目?
Here's an example of the index used:
以下是所用索引的示例:
In[526]: dfa.index[:5]
Out[526]: Index([21:12:19, 21:12:20, 21:12:21, 21:12:21, 21:12:22], dtype='object')
In[527]: type(dfa.index[0])
Out[527]: datetime.time
采纳答案by Alex
Liam's link looks great, but also check out pandas.Timedelta
- looks like it plays nicely with NumPy's and Python's time deltas.
Liam 的链接看起来很棒,但也可以查看pandas.Timedelta
- 看起来它与 NumPy 和 Python 的时间增量配合得很好。
https://pandas.pydata.org/pandas-docs/stable/timedeltas.html
https://pandas.pydata.org/pandas-docs/stable/timedeltas.html
pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)
回答by Philippe Remy
This one worked for me:
这个对我有用:
>> print(df)
TotalVolume Symbol
2016-04-15 09:00:00 108400 2802.T
2016-04-15 09:05:00 50300 2802.T
>> print(cur_df.set_index(pd.to_datetime(cur_df.index.values) - datetime(2016, 4, 15)))
TotalVolume Symbol
09:00:00 108400 2802.T
09:05:00 50300 2802.T
回答by Adam Kuzański
The Philippe solution but cleaner:
菲利普解决方案,但更清洁:
My subtraction data is: '2018-09-22T11:05:00.000Z'
我的减法数据是:'2018-09-22T11:05:00.000Z'
import datetime
import pandas as pd
df_modified = pd.to_datetime(df_reference.index.values) - datetime.datetime(2018, 9, 22, 11, 5, 0)