首页 > 解决方案 > 将熊猫数据框的索引设置为浮点数列表?

问题描述

我有一个主 DF,然后是一个子 DF,我想在主 DF 中插入两行之间。所以第一个 DF 的索引是 ..., 183, 184, 185, 186, 187... 我想在主 DF 的第 185 行和第 186 行之间插入一个五行 DF。

为此,我尝试将子 DF 的索引设置为 185 到 186 之间的数字,然后重新索引,但我在第一行遇到了关键错误。

索引列表为 [185.01, 185.02, 185.03, 185.04, 185.05]。错误是“KeyError:185.01”

我觉得这应该可以基于这个线程:Is it possible to insert a row at a absolute position in a dataframe using pandas?

        # reset then set index for inserting these rows after the rest of the items for this subtest
        row_index.clear()
        row_index = [round((last_subtest_item_index + 0.01) + (x * 0.01),2) for x in range(0, var_counter)]
        print(last_subtest_item_index, row_index)
        print(new_custom_table)

        # TRY TO INSERT THE CUSTOM TABLE DF INTO THE MAIN DF AND SEE IF IT GOES IN-LINE WITH THE REST OF THAT CRF
        new_custom_table.set_index(keys = row_index, inplace = True)
        self.full_CRF = self.full_CRF.append(new_custom_table, ignore_index = False).sort_index().reset_index(drop=True)

标签: pythonpandasindexing

解决方案


问题是它DataFrame.reset_index(keys=keys)需要keys是, 或(链接到 docsSeries ) 类型,但是你给它一个 python 列表,. 解决方法是将列表包装在一个 numpy构造函数中。Indexnumpy.ndarrayrow_indexarray

替换这一行:

new_custom_table.set_index(keys = row_index, inplace = True)

有了这个:

new_custom_table.set_index(keys=pd.np.array(row_index), inplace=True)

推荐阅读