首页 > 解决方案 > 如何获取我的 pandas 层次索引之一和一个热编码?

问题描述

我从按时间索引的帧创建了一个多层次索引:

original_thing
 time                day_1  day_2  day_3 day_4
 2018-05-24 20:00:00  0     0      1     0
 2018-05-25 00:00:00  0     0      0     1
 2018-05-25 04:00:00  0     0      0     1
 2018-05-25 08:00:00  0     0      0     1

将信息重新采样并聚合为不同的对象,并将它们打包到一个列表中

 DF_list = [original_thing, resampled_1, resampled_2]

使用 pandas concat 的代码看起来像这样:

thisthing = pandas.concat(DF_list, keys=range(len(DF_list), names=['one','time'], sort=True)

得到一个看起来像这样的数据框:

one  time                   day_1    day_2    day_3    day_4
 2    2018-05-24 00:00:00    0        0        1        0
 1    2018-05-24 12:00:00    0        0        1        0
 0    2018-05-24 20:00:00    0        0        1        0
 0    2018-05-25 00:00:00    0        0        0        1
 1    2018-05-25 00:00:00    0        0        0        1
 2    2018-05-25 00:00:00    0        0        0        1
 0    2018-05-25 04:00:00    0        0        0        1
 0    2018-05-25 08:00:00    0        0        0        1

我想采用索引“一”并获得:

one  time                   id_1  id_2  id_3 day_...    
 2    2018-05-24 00:00:00    0     0     1    0
 1    2018-05-24 12:00:00    0     1     0    0
 0    2018-05-24 20:00:00    1     0     0    0
 0    2018-05-25 00:00:00    1     0     0    1
 1    2018-05-25 00:00:00    0     1     0    1
 2    2018-05-25 00:00:00    0     0     1    1
 0    2018-05-25 04:00:00    1     0     0    1
 0    2018-05-25 08:00:00    1     0     0    1

id_'#''one' 的编码索引在哪里

我尝试使用以下方式对其进行编码:

conc_ohlc_dummies= pandas.get_dummies(conc_ohlc['one'], prefix= 'hours')

但我收到此错误:

return self._engine.get_loc(self._maybe_cast_indexer(key)) 文件“pandas_libs\index.pyx”,第 140 行,在 pandas._libs.index.IndexEngine.get_loc 文件“pandas_libs\index.pyx”,第 162 行,在 pandas ._libs.index.IndexEngine.get_loc 文件“pandas_libs\hashtable_class_helper.pxi”,第 1492 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item 文件“pandas_libs\hashtable_class_helper.pxi”,第 1500 行,在 pandas._libs.hashtable.PyObjectHashTable .get_item KeyError: '一个'

我还尝试重新索引它以消除索引值。除了写入 csv 并重新打开来执行此操作之外,还有其他方法吗?

谢谢大家

标签: pandasmulti-index

解决方案


最初我试图使用 .reindex() 方法删除数据帧中的任何索引,但发现 .reset_index() 有效。随着索引的方式 .get_dummies() 和 .merge() 编码并将信息添加回我的框架。我确实必须再次设置索引,然后进行排序以获得良好的度量:

    thisthing= thisthing.reset_index()
    thisthing_dummies= pandas.get_dummies(thisthing['one'], prefix='hours', drop_first=True)
    thisthing= thisthing.merge(thisthing_dummies, left_index=True, right_index=True)
    thisthing= thisthing.set_index(['time','one'])
    thisthing.sort_values(by=['time', 'one'],inplace=True)

推荐阅读