首页 > 解决方案 > python: drop_duplicates(subset='col_name', inplace=True),为什么有些行不能被删除?

问题描述

我将通过其中一列删除重复项,但可以删除某些行。

连线的事情是:如果我直接读取 2 个文件而不是通过我的 func1、func2,然后应用 drop 函数,一切都很好!

update1:​​非常喜欢 unicode 问题(感谢 furkanayd),如何解决?

有没有人可以帮忙?谢谢!这是我的代码:

def func1(file):
    try:
        df1 = pd.read_csv('balba', encoding='utf8', low_memory=False)
    except UnicodeDecodeError:
        df1 = pd.read_csv('balba', encoding='gb18030', low_memory=False)
    """select the col_name, then replace ' ' with ''
    """
    return df1

def func2(file):
    df2 = pd.read_csv('balba')
    """select the col_name, then replace ' ' with '', then rename the column name
    """
    turn df2


df2 = func2(file_df2)

DF1 = []
for i in ['one_file_this_time']:
    d = func1(i)
    DF1.append(d)
df1 = pd.concat([DF1], sort=False)
df1.drop_duplicates(inplace=True)

df = pd.concat([df1, df2], sort=False)
print(df.shape)
# (7749, 2)

df.drop_duplicates(subset='col_name', inplace=True)
print(df.shape)
print(df.duplicated().any())
# (5082, 2)
# False
"""obviously the drop_duplicates() functions works, but not fullly"""

在 drop 函数之前,连接的数据是(我将其存储为 csv 格式): 在此处输入图像描述

下降功能后 在此处输入图像描述

标签: pythonpandassubsetdrop-duplicates

解决方案


您应该考虑在您的 drop_duplicates 方法中添加 keep 参数,如此处所述

现在您的代码遵循以下原则:

first :删除除第一次出现的重复项。

没有重复的合并可能会对您有所帮助。这个问题与Pandas 合并创建不需要的重复条目非常相似


推荐阅读