+-
python – 查找Pandas中重复列的重复位置
我知道我可以找到重复的列使用:

df.T.duplicated()

我想知道重复列是重复的索引.例如,C和D都是下面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'])
最佳答案
我不知道重复是否有选项可以提供有关具有相同数据的第一行的信息.我的想法是使用groupby和transform,例如:

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

在您的示例中,arr_first等于数组([‘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中重复列的重复位置 - 乐贴网