【问题标题】:Dropping duplicate rows in data frame with pandas df.drop(), not df.drop_duplicates使用 pandas df.drop() 删除数据框中的重复行,而不是 df.drop_duplicates
【发布时间】:2021-11-19 02:47:07
【问题描述】:

全部 -

我一直在用这段代码兜圈子。我有一个包含 2018、2019、2020 和 2021 年数据的数据框。有时会有重复的行,但由于索引不同,pd.drop_duplicates 不起作用,经过几个小时的故障排除后,我决定删除所有行当我清理我的数据集时可能有重复的行;但是,当我运行下面的代码并提取新的干净 pandas df 时,我在 for 循环中删除的行不会从 df 中删除。

我找到唯一值的“POS”变量是一个位置标识符。

positions = np.unique(df[['POS']].values).flatten().tolist() #find all unique positions

for position in positions:
    index2 = df.index[df['POS'] == position].tolist() #recall index of unique positions
    
    #if then deletes all records and their duplicate
    if int(len(index2)) > 4:
        for i in index2:
            df.drop(i)

非常感谢任何帮助或指导! :)

【问题讨论】:

  • drop dupes 应该可以工作,您可能没有正确使用它。- 索引无关紧要。尝试df.drop_duplicates(subset=[group of columns that contain the dupes], keep='first') 也不要在熊猫中使用循环它是一种反模式

标签: python pandas dataframe unique drop-duplicates


【解决方案1】:

如果您希望您的更改反映在同一个数据框中,您可以在 drop 方法中使用 inplace 参数。 Source

df.drop(i, inplace = True)

【讨论】:

  • 答案需要更多的澄清和细节。
  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-23
  • 2022-10-07
  • 2021-12-06
  • 1970-01-01
相关资源
最近更新 更多