python - 将熊猫数据框的索引设置为浮点数列表?
问题描述
我有一个主 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)
解决方案
问题是它DataFrame.reset_index(keys=keys)
需要keys
是, 或(链接到 docsSeries
) 类型,但是你给它一个 python 列表,. 解决方法是将列表包装在一个 numpy构造函数中。Index
numpy.ndarray
row_index
array
替换这一行:
new_custom_table.set_index(keys = row_index, inplace = True)
有了这个:
new_custom_table.set_index(keys=pd.np.array(row_index), inplace=True)
推荐阅读
- python - Panda.Read_CSV Usecols 不会在 Python 3.9 中将输出打印为列表
- excel - 错误模块名称:在 Windows Server 2019 中通过 VBScript 运行 EXCEL 时出现 KERNELBASE.dll
- sql - 在选择查询中选择不同和自动增量字段
- google-cloud-platform - Cloud Functions 内部流量 - 它是否包括*桥接*边界?
- python - Python SyntaxError ',' 或 ') 预期
- python-3.x - Matplotlib 错误:命令出错,退出状态为 1:python setup.py egg_info 检查日志以获取完整的命令输出
- sqlite - 无法使用 TEXT 数据类型 SQLite3 创建表
- python - Plotly Dash dcc.Interval 实时更新不起作用(使用工作代码示例和数据)
- google-cloud-platform - 查询计数的 GCP BQ 指标未反映正确 否
- apache-flink - flink 工作效率低下,例如: INSERT INTO hive_table select orgId, 2.0 , pdate, '02' from users limit 10000 where user is a kafka table