python - Pandas :将 int64 年转换为仅显示年份的日期时间

标签 python pandas datetime dataframe

我有一个如下所示的数据帧索引:

df.index
Int64Index([1992, 1993, 1994, 1995], dtype='int64')

但希望它转换为日期时间,同时仅显示年份,从而保留上述年度格式。

我试过: Pandas: how to convert an index of int64 years to datetime

import pandas as pd
df.index = pd.to_datetime(df.index, format='%Y')

但这给了我:

DatetimeIndex(['1992-01-01', '1993-01-01', '1994-01-01', '1995-01-01'], dtype='datetime64[ns]', freq=None)

相反,有没有更好的方法我可以按照以下方式获得一些东西:

DatetimeIndex(['1992', '1993', '1994', '1995'], dtype='datetime64)

最佳答案

PeriodIndex呢? ?

In [131]: i = pd.Int64Index([1992, 1993, 1994, 1995], dtype='int64')

In [132]: pd.PeriodIndex(i, freq='A')
Out[132]: PeriodIndex(['1992', '1993', '1994', '1995'], dtype='period[A-DEC]', freq='A-DEC')

关于python - Pandas :将 int64 年转换为仅显示年份的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47531712/

相关文章:

python - Matplotlib:如何将时间戳与 broken_barh 一起使用?

python - 从 PySpark 的 RDD 中的数据中查找最小和最大日期

python - 将 dict 中的列表作为值更改为 dict 中的正常值

python - 当模块名称中包含 '-' 破折号或连字符时如何导入模块?

python - 使用 Pandas 根据该行中的值从 csv 文件中删除特定行之前的行

python - 为什么 pandas DataFrame 比 numpy ndarray 贵?

python - Pandas Dataframe 同时拆分列列表

mysql - 如何将总和转换为时间 - mysql

html - 如何将自定义字体添加到 html 代码中

python - Django:如何更改默认注册字段