我对过滤和提取 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 列(col4
和 col5
)。例如,假设我有 (*)
:
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
我知道我可以使用 duplicated和 groupby用于执行此操作的内置函数。但是,由于我正在处理大量的列和行,所以我不知道这是否会返回我想要的所有重复行。我试图:
在:
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/