【发布时间】:2022-01-06 10:19:13
【问题描述】:
在我的数据框中,我将每列的索引设置为“时间”,然后执行frame = frame.astype(float) 将所有其他数据转换为浮点数。但是,我现在需要默认索引(0、1、2 等),但我仍然想将“时间”列设置为日期时间格式。我尝试了几种不同的方法,它们要么工作,但搞砸了时间(说是 1970 年而不是 2021 年),要么导致TypeError: Cannot cast DatetimeArray to dtype float64
这类似于我想要的数据框(但时间搞砸了):
Time Open High Low Close
0 1970-01-01 00:27:18.185760 57141.92 57157.16 57141.92 57147.00
1 1970-01-01 00:27:18.185820 57145.48 57149.15 57124.62 57139.75
2 1970-01-01 00:27:18.185880 57126.75 57173.11 57126.74 57142.20
3 1970-01-01 00:27:18.185940 57163.42 57163.42 57079.10 57135.31
4 1970-01-01 00:27:18.186000 57084.42 57110.00 57084.42 57092.95
我尝试使用以下命令更改“时间”列的格式:
frame['Time'] = pd.to_datetime(frame['Time'])
和
frame['Time'] = frame['Time'].apply(pd.to_datetime)
我也尝试过以类似的方式更改其他列的类型
frame[['Open','High','Low','Close']] = frame[['Open','High','Low','Close']].apply(frame.astype(float))
我在申请pd.to_datetime之前和之后都试过这个
编辑
将提供更多信息,因为我不够具体。下面的代码从 API 检索数据并将其放入 DataFrame。 API 的响应是一个列表列表,每个子列表包含 10 个元素(我想,现在不记得了)。我只希望数据达到“关闭”。
def get_historical_futures_data(symbol, interval, lookback):
frame = pd.DataFrame(client.futures_historical_klines(symbol, interval, lookback+' min ago UTC'))
frame = frame.iloc[:,:5]
frame.columns = ['Time','Open','High','Low','Close']
frame = frame.set_index('Time')
frame.index = pd.to_datetime(frame.index, unit='ms')
frame = frame.astype(float)
print(frame)
frames.append(frame)
Open High Low Close
Time
2021-11-29 14:27:00 57220.49 57220.50 57185.95 57190.01
2021-11-29 14:28:00 57190.00 57209.21 57161.74 57177.28
2021-11-29 14:29:00 57177.28 57182.61 57160.26 57164.46
2021-11-29 14:30:00 57164.46 57186.99 57154.32 57155.99
2021-11-29 14:31:00 57156.00 57179.74 57154.33 57179.74
上面是代码(及其输出),我以前有,但是,在我的代码的另一部分,我意识到保留行索引号对我来说要容易得多,所以我不想'时间' 每行的索引。相反,我希望保留每一行的索引,然后是其余的数据框,类似于:
Time Open High Low Close
0 1970-01-01 00:27:18.185760 57141.92 57157.16 57141.92 57147.00
1 1970-01-01 00:27:18.185820 57145.48 57149.15 57124.62 57139.75
2 1970-01-01 00:27:18.185880 57126.75 57173.11 57126.74 57142.20
3 1970-01-01 00:27:18.185940 57163.42 57163.42 57079.10 57135.31
4 1970-01-01 00:27:18.186000 57084.42 57110.00 57084.42 57092.95
我的问题是,我无法将“时间”列设为 DateTime 类型,也无法将其他列(Open、High、Low、Close)设为浮点类型。我要么收到关于类型转换的错误,要么时间列搞砸了,说的是 1970 年而不是 2021 年。
如何让每一列(EXCEPT FOR TIME)为float类型,而将Time列设为DateTime类型?
【问题讨论】:
-
不确定我是否理解这个问题。您是否运行了“错误”命令并想要“取消”?你不能重新启动你的脚本/笔记本吗?您能否提供一个重现问题的最小示例(提供输入数据)?
-
你不能只是
frame.reset_index(),这应该给你时间索引作为一列和一个从 0 到 n 的新索引? -
不确定问题出在哪里 - 您是说您的
DataFrame中有一个包含“浮点数”的“时间”列吗?或者您是说您的“时间”列有“类似日期时间的条目”并且您无法将其转换为正确的日期时间值?
标签: python pandas dataframe datetime