返回列

时间:2017-05-25 06:41:24

标签: python pandas

我正在尝试在2列中找到具有唯一值对的行,因此这个数据帧:

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
如果翻转,

将仅缩减为不匹配的行,例如1和3是我只想返回一次的组合。因此,如果列被翻转(3和1),则检查是否存在相同的对,可以将其删除。我想要的表是:

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

如果翻转列,则每对镜像值只出现一次。

2 个答案:

答案 0 :(得分:4)

我认为您可以使用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

使用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

不使用DataFrame.minDataFrame.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 :(得分:1)

加载数据:

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))

如果您不需要对整个DF进行排序:

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