首页 > 解决方案 > 我想重置索引,但想拥有数据框中的所有列

问题描述

                          a       b           ...          c         d
DateTime                                      ...                       

2016-07-01 00:00:00  994.758209  31.556425    ...          NaN       NaN

2016-07-01 12:00:00  994.727417  29.273750    ...          NaN       NaN

2016-07-02 00:00:00  996.516484  26.598056    ...          NaN       NaN

2016-07-04 00:00:00  997.588235  10.686389    ...          NaN       NaN

2016-07-04 12:00:00  994.347107  25.472639    ...          NaN       NaN

我的索引是日期时间,但我想设置默认索引,0,1...to n但想将我的日期时间索引保留为数据框中的列。

reset_index()删除索引,我无法将日期时间作为列获取。

我怎样才能做到这一点?

标签: pythonpandasdataframe

解决方案


df = pd.read_csv('data.csv', parse_dates=['DateTime'], index_col='DateTime')

                             a          b
           DateTime     
2016-07-01 00:00:00 994.758209  31.556425
2016-07-01 12:00:00 994.727417  29.273750
2016-07-02 00:00:00 996.516484  26.598056
2016-07-04 00:00:00 997.588235  10.686389
2016-07-04 12:00:00 994.347107  25.472639

df.info()

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 5 entries, 2016-07-01 00:00:00 to 2016-07-04 12:00:00
Data columns (total 2 columns):
a    5 non-null float64
b    5 non-null float64
dtypes: float64(2)

df = df.reset_index()

               DateTime          a          b
0   2016-07-01 00:00:00 994.758209  31.556425
1   2016-07-01 12:00:00 994.727417  29.273750
2   2016-07-02 00:00:00 996.516484  26.598056
3   2016-07-04 00:00:00 997.588235  10.686389
4   2016-07-04 12:00:00 994.347107  25.472639

df.reset_index()不应删除该DateTime

如果这不能解决问题,请在原始问题中发布您的代码。


推荐阅读