【问题标题】:python: drop_duplicates(subset='col_name', inplace=True), why some of the rows can not be dropped?python: drop_duplicates(subset='col_name', inplace=True),为什么有些行不能被删除?
【发布时间】:2020-03-26 20:32:54
【问题描述】:

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

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

更新1: 非常喜欢 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 格式):

后放功能

【问题讨论】:

  • 发布一些数据..会有所帮助
  • 很难描述您的问题。向我们展示您的一些数据样本。

标签: python pandas subset drop-duplicates


【解决方案1】:

您应该考虑在您的 drop_duplicates 方法中添加 keep 参数,如提到的 here

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

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

没有重复的合并可能会对您有所帮助。这个问题和Pandas merge creates unwanted duplicate entries很像

【讨论】:

  • @span class="comcopy">keep='first 添加后仍然得到重复的行~~
  • @Sean.H 通过检查逻辑运算符,您确定认为重复的值没有不同。
  • 是的,我确定。我制作了 2 个测试数据文件。 1)如果我通过我的 func 得到了 df1 和 df2(请在上面找到它们),然后是 concat,最后是 drop_duplicates(),我得到的是问题之一。但是,2)如果我直接读取2个测试文件而不是通过我的func,我得到的没有问题~~唉,不知道为什么。
  • 据我从代码和您的帖子中了解到,字符串类型可能会导致 read_csv 的这种 unicode 翻译可能有助于解决这个问题,因为它在此处进行了解释:stackoverflow.com/questions/904041/…
  • 谢谢。 df.duplicated().any() 返回False。那么问题来了,如何解决这个极有可能的 unicode 问题呢?例如一个带有 unicode_A 的文件,另一个带有 unicode_B 的文件?
猜你喜欢
  • 2017-08-08
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2012-09-22
  • 1970-01-01
  • 1970-01-01
  • 2012-04-09
  • 1970-01-01
相关资源
最近更新 更多