如何为日期索引创建新列

时间:2018-04-16 23:46:08

标签: python pandas

我想为日期索引创建一个新列。这是我的数据集

 score          <80   80-100
 data
 2018-01-01      3        5
 2018-01-02      6        3

这是特征

In [150] df.columns

Out[150] CategoricalIndex(['<80', '80-100'], categories=['<80', '80-100'], ordered=True, name='final_score', dtype='category')

In [151] df.index

Out[151] Index([2018-01-01, 2018-01-02],
         dtype='object', name='date')

我想将索引转换为列,例如,我尝试的是

df['date'] = df.index

但是,它不起作用

2 个答案:

答案 0 :(得分:1)

您正在寻找df.set_index()

df.set_index('date', inplace=True)

答案 1 :(得分:1)

您需要reset_index + rename

df.columns=df.columns.astype(str)
df.reset_index().rename(columns={'data':'date'})
Out[575]: 
score        date  <80  80-100
0      2018-01-01    3       5
1      2018-01-02    6       3
相关问题