[英]Set_index of pandas dataframe to list of floats?
I have a main DF and then a sub-DF that I want to insert within the main DF, between two rows. 我有一个主DF,然后有一个要插入主DF的两行之间的子DF。 So the index of the first DF is ..., 183, 184, 185, 186, 187... I want to insert a five-row DF in between rows 185 and 186 in the main DF. 因此,第一个DF的索引是...,183、184、185、186、187 ...我想在主DF的行185和186之间插入一个五行DF。
To do this, I am trying to set the index of the sub-DF to numbers between 185 and 186, and then reindex, but I am getting a key error on the first row. 为此,我试图将子DF的索引设置为185和186之间的数字,然后重新索引,但是第一行却遇到关键错误。
The index list is [185.01, 185.02, 185.03, 185.04, 185.05]. 索引列表是[185.01、185.02、185.03、185.04、185.05]。 The error is "KeyError: 185.01" 错误为“ KeyError:185.01”
I feel like this should be possible based on this thread: Is it possible to insert a row at an arbitrary 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)
The problem is that DataFrame.reset_index(keys=keys)
requires keys
to be of type Series
, Index
, or numpy.ndarray
( link to docs ), but you're giving it a python list, row_index
. 问题是DataFrame.reset_index(keys=keys)
要求keys
的类型为Series
, Index
或numpy.ndarray
( 链接到docs ),但是您numpy.ndarray
它提供一个python列表row_index
。 The fix is to wrap the list in a numpy array
constructor. 解决方法是将列表包装在numpy array
构造函数中。
Replace this line: 替换此行:
new_custom_table.set_index(keys = row_index, inplace = True)
with this: 有了这个:
new_custom_table.set_index(keys=pd.np.array(row_index), inplace=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.