2
votes

I'm trying to find rows that have unique pairs of values across 2 columns, so this dataframe:

A    B
1    0
2    0
3    0
0    1
2    1
3    1
0    2
1    2
3    2
0    3
1    3
2    3

will be reduced to only the rows that don't match up if flipped, for instance 1 and 3 is a combination I only want returned once. So a check to see if the same pair exists if the columns are flipped (3 and 1) it can be removed. The table I'm looking to get is:

A  B
0  2
0  3
1  0
1  2
1  3
2  3

Where there is only one occurrence of each pair of values that are mirrored if the columns are flipped.

2

2 Answers

4
votes

I think you can use apply sorted + drop_duplicates:

df = df.apply(sorted, axis=1).drop_duplicates()
print (df)
   A  B
0  0  1
1  0  2
2  0  3
4  1  2
5  1  3
8  2  3

Faster solution with numpy.sort:

df = pd.DataFrame(np.sort(df.values, axis=1), index=df.index, columns=df.columns)
      .drop_duplicates()
print (df)
   A  B
0  0  1
1  0  2
2  0  3
4  1  2
5  1  3
8  2  3

Solution without sorting with DataFrame.min and DataFrame.max:

a = df.min(axis=1)
b = df.max(axis=1)
df['A'] = a
df['B'] = b
df = df.drop_duplicates()
print (df)
   A  B
0  0  1
1  0  2
2  0  3
4  1  2
5  1  3
8  2  3
1
votes

Loading the data:

import numpy as np
import pandas as pd

a = np.array("1 2   3   0   2   3   0   1   3   0   1   2".split("\t"),dtype=np.double)
b = np.array("0 0   0   1   1   1   2   2   2   3   3   3".split("\t"),dtype=np.double)
df = pd.DataFrame(dict(A=a,B=b))

In case you don't need to sort the entire DF:

df["trans"] = df.apply(
  lambda row: (min(row['A'], row['B']), max(row['A'], row['B'])), axis=1
)
df.drop_duplicates("trans")