在 Pandas 中查找重复列的重复位置
Finding the Location of the Duplicate for Duplicated Columns in 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'])
我不知道 duplicated
是否可以选择提供有关具有相同数据的第一行的信息。我的想法是使用 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
等于 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
另一种更直接的测试两个数字列是否相互重复的方法是测试相关矩阵,它测试所有的列对。这是代码:
import pandas as pd
df = pd.DataFrame([[1,0,1,1], [2,0,2,2]], columns=['A', 'B', 'C', 'D'])
# compute the correlation matrix
cm = df.corr()
cm
这显示了所有列与其他列(包括它本身)之间的相关性矩阵。如果一列是 1:1 与另一列,则该值为 1.0.
要查找与 A 重复的所有列,则:
cm['A']
A 1.0
B NaN
C 1.0
D 1.0
如果您有分类(字符串对象)而不是数字,您可以进行互相关 table。
希望对您有所帮助!
我知道我可以使用以下方法找到重复的列:
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'])
我不知道 duplicated
是否可以选择提供有关具有相同数据的第一行的信息。我的想法是使用 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
等于 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
另一种更直接的测试两个数字列是否相互重复的方法是测试相关矩阵,它测试所有的列对。这是代码:
import pandas as pd
df = pd.DataFrame([[1,0,1,1], [2,0,2,2]], columns=['A', 'B', 'C', 'D'])
# compute the correlation matrix
cm = df.corr()
cm
这显示了所有列与其他列(包括它本身)之间的相关性矩阵。如果一列是 1:1 与另一列,则该值为 1.0.
要查找与 A 重复的所有列,则:
cm['A']
A 1.0
B NaN
C 1.0
D 1.0
如果您有分类(字符串对象)而不是数字,您可以进行互相关 table。
希望对您有所帮助!