我有一个名为"keytable“的数据框架,它的特点是一个由”月“、”日“和”小时“组成的多索引。我想保留多个索引,同时创建3个值为'Month','Day‘和'Hour’的新列。我该怎么做呢?以下是数据帧:
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]发布于 2020-05-08 00:27:32
要创建名为‘月’、‘日’、‘年’的新列,只需使用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) 应该行得通。
发布于 2020-05-08 00:46:18
我最终执行了一个reset_index()并取消删除了一个datetime列,这样我就可以对它进行重新索引。
keytable=keytable.reset_index()
keytable['datetime'] = pd.to_datetime(keytable['datahora'].str.replace('/','-'), errors='coerce')
keytable=keytable.set_index('datetime')https://stackoverflow.com/questions/61662711
复制相似问题