熊猫:如何创建日期时间索引

时间:2020-10-16 09:49:08

标签: python-3.x pandas dataframe

Pandas数据框为:

    year    month   count
0   2014    Jan     12
1   2014    Feb     10
2   2015    Jan     12
3   2015    Feb     10

如何从“年”和“月”创建DateTime索引,结果将是:

              count
2014.01.31    12
2014.02.28    10
2015.01.31    12
2015.02.28    10

1 个答案:

答案 0 :(得分:2)

to_datetimeDataFrame.pop一起使用,并删除列并添加offsets.MonthEnd

dates = pd.to_datetime(df.pop('year').astype(str) + df.pop('month'), format='%Y%b')
df.index = dates + pd.offsets.MonthEnd()

print (df)
            count
2014-01-31     12
2014-02-28     10
2015-01-31     12
2015-02-28     10

或者:

dates = pd.to_datetime(df.pop('year').astype(str) + df.pop('month'), format='%Y%b')
df.index = dates + pd.to_timedelta(dates.dt.daysinmonth - 1, unit='d')

print (df)
            count
2014-01-31     12
2014-02-28     10
2015-01-31     12
2015-02-28     10