python - 如何过滤 Pandas 数据框中按索引分组的重复行?

标签 python python-3.x pandas dataframe pandas-groupby

我对过滤和提取 Pandas 数据框中的重复行感到困惑。例如,考虑:

   col1     col2      col3   col4  col5    ID

    1        yes        0      1      2    201
    2         0         1      0      0    203
    0         0         0      0      1    202
    0         0         0      0      2    202
    1        yes        0      3      4    201

如何在不考虑特定列数的情况下选择所有具有相同关联 ID 的重复行并将其排列到另一个 pandas 数据框中,让我们假设此示例的最后 2 列(col4col5)。例如,假设我有 (*):

   col1     col2      col3   col4  col5    ID

    1        yes        0      1      2    201
    1        yes        0      3      4    201
    0         0         0      0      1    202
    0         0         0      0      2    202
    2         0         1      0      0    203

我知道我可以使用 duplicatedgroupby用于执行此操作的内置函数。但是,由于我正在处理大量的列和行,所以我不知道这是否会返回我想要的所有重复行。我试图:

在:

temp2 = ['col4','col5']
# I am doing this because I have a lot of columns in my real dataset more than 800
a_lis = list(set(df.columns) - set(temp2))
a_lis

df.groupby(df['ID']).loc[df.duplicated(keep=False, subset=a_lis),:]

输出:

AttributeError: Cannot access callable attribute 'loc' of 'DataFrameGroupBy' objects, try using the 'apply' method

我的困惑来自于 keep 参数,我完全不明白这个参数是如何工作的。因此,我的问题是如何正确使用 groupby 和 keep 参数来获取 (*)

最佳答案

你不需要在这里使用groupby。只需使用 pd.DataFrame.loc。请记住,groupby 用于通过函数聚合数据。但是您似乎想要的是 reindex 并将重复的行放在数据框的顶部。

keep=False 保留数据框中其他地方有重复的所有行,只考虑 subset 中的列。在这种情况下,索引为 1 的行将被删除。

import numpy as np

# calculate duplicate indices
dup_index = df[df.duplicated(keep=False, subset=a_lis)].sort_values('ID').index

# calculate non-duplicate indices
non_dup_index = df.index.difference(dup_index)

# concatenate and reindex
res = df.reindex(np.hstack((dup_index.values, non_dup_index.values)))

print(res)

   col1 col2  col3  col4  col5   ID
0     1  yes     0     1     2  201
4     1  yes     0     3     4  201
2     0    0     0     0     1  202
3     0    0     0     0     2  202
1     2    0     1     0     0  203

关于python - 如何过滤 Pandas 数据框中按索引分组的重复行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51070127/

相关文章:

python - 检测彩色圆圈

python - 这是在 python 中打开 'complicated' txt 文件的好方法

python - 减小 cPickle 对象的大小

python-3.x - 计算同一组中有多少行在 Pandas DataFrame 中的每一行的给定列中具有较大的值

python - 在python中将本地时间从UTC更改为UTC + 2

python - 根据第一列中的模式更改在 Pandas 数据框中创建新列

python - psutil.test() 返回无。如何将其输出写入文件?

python-3.x - 使用 OpenCV + Python 播放捕获的视频时出错

python - 从另一个 DataFrame 的索引列表中提取 DataFrame

python - 在两组之后将系列转换为数据框