【问题标题】:Drop duplicates in a subset of columns per row, rowwise, only keeping the first copy, rowwise only if there are 3 or more duplicates在每行的列子集中删除重复项,按行,仅保留第一个副本,仅当有 3 个或更多重复项时按行
【发布时间】:2023-02-25 04:11:26
【问题描述】:

这是我之前问题的扩展,Drop duplicates in a subset of columns per row, rowwise, only keeping the first copy, rowwise

这个问题有两个部分。

我有以下数据框。

import pandas as pd

data = {'date': ['2023-02-22', '2023-02-21', '2023-02-23'],
        'x1': ['descx1a', 'descx1b', 'descx1c'],
        'x2': ['ALSFNHF950', 'KLUGUIF615', np.nan],
        'x3': [np.nan, np.nan, 24319.4],
        'x4': [np.nan, np.nan, 24334.15],
        'x5': [np.nan, np.nan, 24040.11],
        'x6': [np.nan, 75.51, 24220.34],
        'x7': [np.nan, np.nan, np.nan],
        'v': [np.nan, np.nan, np.nan],
        'y': [404.29, np.nan, np.nan],
        'ay': [np.nan, np.nan, np.nan],
        'by': [np.nan, np.nan, np.nan],
        'cy': [np.nan, np.nan, np.nan],
        'gy': [np.nan, np.nan, np.nan],
        'uap': [404.29, 75.33, np.nan],
        'ubp': [404.29, 75.33, np.nan],
        'sf': [np.nan, 2.0, np.nan]}

df = pd.DataFrame(data)

如果在任何列 x3、x4、x5、x6、x7、v、y、ay、by、cy、gy、uap、ubp 中有超过 3 个或更多重复的数字,我想删除重复项并且只保留一个副本,即 x6 列中的副本或副本出现的第一列。

在大多数行中,第一个副本(如果有副本)出现在列 x6 中。

输出应该是这样的,


data = {'date': ['2023-02-22', '2023-02-21', '2023-02-23'],
        'x1': ['descx1a', 'descx1b', 'descx1c'],
        'x2': ['ALSFNHF950', 'KLUGUIF615', np.nan],
        'x3': [np.nan, np.nan, 24319.4],
        'x4': [np.nan, np.nan, 24334.15],
        'x5': [np.nan, np.nan, 24040.11],
        'x6': [np.nan, 75.51, 24220.34],
        'x7': [np.nan, np.nan, np.nan],
        'v': [np.nan, np.nan, np.nan],
        'y': [404.29, np.nan, np.nan],
        'ay': [np.nan, np.nan, np.nan],
        'by': [np.nan, np.nan, np.nan],
        'cy': [np.nan, np.nan, np.nan],
        'gy': [np.nan, np.nan, np.nan],
        'uap': [np.nan, 75.33, np.nan],
        'ubp': [np.nan, 75.33, np.nan],
        'sf': [np.nan, 2.0, np.nan]}

第二行不应该受到影响,因为该数字只有 2 个副本。

上一个问题有答案,

check = ['x3', 'x4', 'x5', 'x6', 'x7', 'v', 'y', 'ay', 'by', 'cy', 'gy', 'uap', 'ubp']
df.loc[:, check] = df.loc[:, check].mask(df.loc[:, check].apply(pd.Series.duplicated, axis=1))
print(df)

但如果我这样做,那么 75.33 中的一个将被删除。那不是我想要的。

我在想也许我可以对每行执行一个 for 循环,然后替换该值,但我有超过 700 万行数据。有任何想法吗?

【问题讨论】:

  • 请注意,重复浮点值并不理想,除非您确定您的值是有限的。

标签: python pandas dataframe


【解决方案1】:

回答是因为显然,您需要 50 声望才能发表评论。是否可以出于您的目的首先创建数据框的副本,然后使用先前答案的解决方案清除重复项,然后遍历它,将数据框列的每个索引处的值与原始值进行比较,并带有一些计数器系统的类型?

【讨论】:

  • 我可能没有足够的 ram 来玩那个哈哈
猜你喜欢
  • 1970-01-01
  • 2012-04-30
  • 2021-12-02
  • 2019-06-02
  • 1970-01-01
  • 1970-01-01
  • 2015-10-26
  • 2016-02-15
  • 1970-01-01
相关资源
最近更新 更多