【发布时间】:2019-05-22 02:37:32
【问题描述】:
我在下面有一个可重现的代码:
import pandas as pd
import datetime
foo = pd.read_csv("http://m.uploadedit.com/bbtc/1545406250692.txt", header=None, names=["Stock","Date","Time", "Open", "High", "Low", "Close", "Volume", "OI"], dtype={"Stock":"category"}, parse_dates= [['Date', 'Time']], index_col="Date_Time")
foo.sort_index(inplace=True)
bar = foo.between_time('09:00:00', '15:30:00') #Dropping post and pre market data i.e. from index 15:31 - 16:35
#resampling the data by 120 Minutes (2 hours)
twohour = bar.loc["2018-11-22 09:08:00":].resample('120Min',closed = 'right',label = 'left', base=75).agg({'Open': 'first', 'High': 'max', 'Low': 'min','Close': 'last'}).dropna()
twohour.head(7)
Out[]:
Close High Open Low
Date_Time
2018-11-22 07:15:00 321.3 321.30 321.30 321.30
2018-11-22 09:15:00 324.5 326.90 320.10 320.00
2018-11-22 11:15:00 323.2 324.85 324.60 322.20
2018-11-22 13:15:00 319.9 324.35 323.20 319.50
2018-11-22 15:15:00 320.0 320.35 319.85 319.15
2018-11-26 07:15:00 324.90 324.90 324.90 324.90
2018-11-26 09:15:00 311.35 324.40 323.10 309.60
我希望时间为09:15:00 的索引中Open 列中的每个值都替换为时间为07:15:00 的索引中Close 列的值。
简而言之,我需要这个输出:
Out[]:
Close High Open Low
Date_Time
2018-11-22 07:15:00 321.3 321.30 321.30 321.30
2018-11-22 09:15:00 324.5 326.90 321.30 320.00
2018-11-22 11:15:00 323.2 324.85 324.60 322.20
2018-11-22 13:15:00 319.9 324.35 323.20 319.50
2018-11-22 15:15:00 320.0 320.35 319.85 319.15
2018-11-26 07:15:00 324.90 324.90 324.90 324.90
2018-11-26 09:15:00 311.35 324.40 324.90 309.60
我尝试通过将DateTimeindex 转换为字典然后替换值来使用.loc。但是字典没有排序,所以它需要对字典进行排序,代码变得越来越难看。
任何帮助将不胜感激。
【问题讨论】:
-
在您的 DataFrame 中,有两行的“Date_Time”列值为“07:15:00”。替换时如何决定选择哪一个?
-
在您有 9:15 的数据但没有 7:15 的记录的日期应该发生什么?
-
@L.B.如输出所示,我想用时间 9:15:00 替换索引上方的那个。
-
@ALollz 这不会发生,但如果发生了,我不想改变任何东西,我会保持数据不变。
-
@L.B.还没有,接下来 15 分钟试试。
标签: python pandas datetime dataframe