将单个 Pandas 列转换为 DateTime

Mo0*_*rBy 0 python datetime dataframe pandas

在我的数据框中,我将每列的索引设置为“时间”,然后将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
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下方法更改“时间”列的格式:

frame['Time'] = pd.to_datetime(frame['Time'])
Run Code Online (Sandbox Code Playgroud)

frame['Time'] = frame['Time'].apply(pd.to_datetime)
Run Code Online (Sandbox Code Playgroud)

我也尝试以类似的方式更改其他列的类型

frame[['Open','High','Low','Close']] = frame[['Open','High','Low','Close']].apply(frame.astype(float))
Run Code Online (Sandbox Code Playgroud)

我在申请之前和之后尝试过这个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)
Run Code Online (Sandbox Code Playgroud)
                         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
Run Code Online (Sandbox Code Playgroud)

上面是我之前的代码(及其输出),但是,在代码的另一部分中,我意识到保留行索引号对我来说要容易得多,所以我不想制作“时间”每行的索引。相反,我希望保留每行的索引,然后保留数据帧的其余部分,类似于:

                          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
Run Code Online (Sandbox Code Playgroud)

我的问题是,我无法将“时间”列设置为 DateTime 类型,也无法将其他列(开盘价、最高价、最低价、收盘价)设置为浮点类型。我要么收到有关类型转换的错误,要么“时间”列变得混乱并显示 1970 年而不是 2021 年。

如何将每一列(时间除外)设置为 float 类型,并将 Time 列设置为 DateTime 类型?

Iva*_*sky 5

我相信这个问题可能会发生,因为 pandas 不容易找到该格式。也许您可以尝试使用infer_datetime_format=True来增强检测到的格式。

请尝试:

frame['Time'] = pd.to_datetime(frame['Time'],infer_datetime_format=True)
Run Code Online (Sandbox Code Playgroud)

这输出

                        Time
0 1970-01-01 00:27:18.185760
1 1970-01-01 00:27:18.185820
2 1970-01-01 00:27:18.185880
Run Code Online (Sandbox Code Playgroud)

通过使用df.info()我们可以检查它是否是实际的日期时间格式:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype         
---  ------  --------------  -----         
 0   Time    3 non-null      datetime64[ns]
dtypes: datetime64[ns](1)
memory usage: 152.0 bytes
None
Run Code Online (Sandbox Code Playgroud)

这是本示例使用的示例数据:

df = pd.DataFrame({'Time':['1970-01-01 00:27:18.185760',
                           '1970-01-01 00:27:18.185820',
                           '1970-01-01 00:27:18.185880']})
Run Code Online (Sandbox Code Playgroud)