繁体   English   中英

在 pandas 数据帧中,如何将 DatetimeIndex 类型的所有索引标签转换为 datetime.datetime?

[英]In pandas dataframes, how would you convert all index labels as type DatetimeIndex to datetime.datetime?

正如标题所说,我正在尝试将我的 DataFrame 标签转换为日期时间类型。 在以下尝试的解决方案中,我将标签从 DataFrame 拉到 dates_index 并尝试使用 function DatetimeIndex.to_datetime 将它们转换为日期时间,但是,我的编译器说 DatetimeIndex 没有属性 to_datetime。

dates_index = df.index[0::]
dates = DatetimeIndex.to_datetime(dates_index)

我也尝试过使用 pandas.to_datetime function。

dates = pandas.to_datetime(dates_index, errors='coerce')

这将返回包含在 DatetimeIndex 中的日期时间,而不仅仅是日期时间。

我的 DatetimeIndex 标签包含日期和时间的数据,我的目标是将这些数据推送到 DataFrame 的两个单独的列中。

如果您的DateTimeIndexmyindex ,那么

df.reset_index()将创建一个 myindex 列,你可以用它做你想做的事情,如果你想稍后再让它成为索引,你可以通过 `df.set_index('myindex') 恢复

您可以在转换列的数据类型后设置索引。

要将数据类型转换为日期时间,请使用: to_datetime并且,要将列设置为索引,请使用: set_index

希望这可以帮助!

import pandas as pd
df = pd.DataFrame({
    'mydatecol': ['06/11/2020', '06/12/2020', '06/13/2020', '06/14/2020'],
    'othcol1': [10, 20, 30, 40],
    'othcol2': [1, 2, 3, 4]
})
print(df)
print(f'Index type is now {df.index.dtype}')
df['mydatecol'] = pd.to_datetime(df['mydatecol'])
df.set_index('mydatecol', inplace=True)
print(df)
print(f'Index type is now {df.index.dtype}')

Output 是

    mydatecol  othcol1  othcol2
0  06/11/2020       10        1
1  06/12/2020       20        2
2  06/13/2020       30        3
3  06/14/2020       40        4
Index type is now int64
            othcol1  othcol2
mydatecol                   
2020-06-11       10        1
2020-06-12       20        2
2020-06-13       30        3
2020-06-14       40        4
Index type is now datetime64[ns]

我找到了一个快速解决我的问题的方法。 您可以根据索引创建一个新的 pandas 列,然后使用 datetime 重新格式化日期。

df['date'] = df.index   # Creates new column called 'date' of type Timestamp
df['date'] = df['date'].dt.strftime('%m/%d/%Y %I:%M%p')  # Date formatting

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM