【问题标题】:Pandas : change the index of the duplicatesPandas:更改重复项的索引
【发布时间】:2020-04-21 21:41:42
【问题描述】:

我有 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

【问题讨论】:

    标签: python-3.x pandas dataframe indexing


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      使用reset_index(drop = True)

      dft.reset_index(drop=True)
      

      【讨论】:

        猜你喜欢
        • 2021-06-09
        • 1970-01-01
        • 2021-09-18
        • 2022-11-21
        • 2015-01-16
        • 2022-01-10
        • 2019-10-15
        • 2013-12-10
        • 2013-04-01
        相关资源
        最近更新 更多