python - 查找 Pandas 中重复列的重复位置

标签 python pandas duplicates data-cleaning

我知道我可以使用以下方法找到重复的列:

df.T.duplicated()

我想知道重复列与其重复的索引。例如,CD 都是下面 A 的副本:

df = pd.DataFrame([[1,0,1,1], [2,0,2,2]], columns=['A', 'B', 'C', 'D'])

   A  B  C  D
0  1  0  1  1
1  2  0  2  2

我想要这样的东西:

duplicate_index = pd.Series([None, None, 'A', 'A'], ['A', 'B', 'C', 'D'])

最佳答案

我不知道 duplicated 是否可以选择提供有关具有相同数据的第一行的信息。我的想法是使用 groupbytransform 例如:

arr_first = (df.T.reset_index().groupby([col for col in df.T.columns])['index']
                .transform(lambda x: x.iloc[0]).values)

在你的例子中,arr_first 等于 array(['A', 'B', 'A', 'A'], dtype=object)因为它们的顺序与 df.columns 相同,所以要获得预期的输出,您可以使用 np.where,例如:

duplicate_index = pd.Series(pd.np.where(arr_first != df.columns, arr_first, None),df.columns)

duplicate_index 的结果是

A    None
B    None
C       A
D       A
dtype: object

关于python - 查找 Pandas 中重复列的重复位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51162242/

相关文章:

python - 计算字段中单词/字符的出现次数

queue - Ocaml 中的重复值

python - 尝试在开发模式下运行 sanic 时出现 ValueError

python - 选择一定范围的数组元素并定义一个新数组

python - 在python中将列表列表转换为数据框

Solr,阻止更新现有文档

MySQL选择其他表中没有匹配列的行

python - while 循环中累积的内存使用量

python - 我可以在一个项目目录中拥有多个 Python fabfile 吗?

python - 在提取子集时如何保留 NAN 值?