熊猫:更改重复索引

时间:2020-01-03 10:10:11

标签: python-3.x pandas dataframe indexing

我有2个数据帧:df0df1df1.shape[0] > df1.shape[0]

df0df1的列完全相同。 df0的大多数行都在df1中。

df0df1的索引是

df0.index = range(df0.shape[0])
df1.index = range(df1.shape[0])

然后我创建了dft

dft = pd.concat([df0, df1], axis=0, sort=False)

并使用

删除重复的行
dft.drop_duplicates(subset='this_col_is_not_index', keep='first', inplace=True)

我在dft的索引上有一些重复项。例如:

dft.loc[3].shape

返回

(2, 38)

我的目的是将返回的第二行的索引更改为具有唯一索引3。 第二行应索引为dft.index.sort_values()[-1]+1

我想将此操作应用于所有重复项。

参考文献:

Python Pandas: Get index of rows which column matches certain value

Pandas: Get duplicated indexes

Redefining the Index in a Pandas DataFrame object

2 个答案:

答案 0 :(得分:1)

将参数ignore_index=True添加到concat以避免重复的索引值:

dft = pd.concat([df0, df1], axis=0, sort=False, ignore_index=True)

答案 1 :(得分:1)

使用reset_index(drop = True)

dft.reset_index(drop=True)