我有一个名为 "keytable "的数据框架,它的特点是由 "月"、"日 "和 "小时 "组成的多索引。我想保留这个多索引,同时创建3个新的列,值为 "月"、"日 "和 "小时"。我如何才能做到这一点?
keytable.head()
Out[59]:
pp pres rad rh ... ws WeekDay Power_kW Power_kW18
Month Day Hour ...
1 3 0 0.0 1027.6 4.1 78.9 ... 0.0 3 77.303046 117.774419
1 0.0 1027.0 3.3 79.7 ... 0.0 3 72.319602 110.710928
2 0.0 1027.0 3.3 81.8 ... 0.0 3 71.831852 106.067667
3 0.0 1027.0 1.9 86.6 ... 0.0 3 69.555751 106.325955
4 0.0 1027.0 3.8 92.2 ... 0.0 3 69.525780 102.855393
[5 rows x 11 columns]
要创建新的列'月'、'日'、'年',只需要 new_table=key_table.reset_index()
就可以了。将索引复制为列是一种非常糟糕的做法,但如果你真的坚持这样做,那么
newdf = new_table[['Year', 'Month', 'Year']].set_index(['Year', 'Month', 'Year']).
new_table.set_index(newdf.index, inplace=True)
应该可以。
最后我做了一个reset_index(),取消了一个datetime列,这样我就可以重新索引它。
keytable=keytable.reset_index()
keytable['datetime'] = pd.to_datetime(keytable['datahora'].str.replace('/','-'), errors='coerce')
keytable=keytable.set_index('datetime')