In [39]: data = """ID#1 0 1 0 1 0 0 1 0 1
ID#2 0 0 1 0 1 0 1 0 1
ID#3 1 0 0 0 1 0 1 1 0
ID#4 0 1 0 1 0 0 1 0 1
ID#5 1 0 0 0 1 0 1 1 0
ID#6 0 0 1 0 1 0 1 0 1
"""
In [40]: df = read_csv(StringIO(data),header=None,sep='\s+',index_col=0)
In [41]: df['compressed'] = df.apply(lambda x: ''.join([ str(v) for v in x ]),1)
In [42]: df
Out[42]:
1 2 3 4 5 6 7 8 9 compressed
0
ID#1 0 1 0 1 0 0 1 0 1 010100101
ID#2 0 0 1 0 1 0 1 0 1 001010101
ID#3 1 0 0 0 1 0 1 1 0 100010110
ID#4 0 1 0 1 0 0 1 0 1 010100101
ID#5 1 0 0 0 1 0 1 1 0 100010110
ID#6 0 0 1 0 1 0 1 0 1 001010101
In [43]: df.groupby('compressed').apply(lambda x: x.index.tolist())
Out[43]:
compressed
001010101 [ID#2, ID#6]
010100101 [ID#1, ID#4]
100010110 [ID#3, ID#5]
dtype: object
这里还有 2 个你可以做的整形(在添加“压缩”列之前做这个)
创建一个系列,其值为 1 个位置的元组
In [45]: pd.concat([ Series([ tuple(x[x.astype(bool)].index.tolist()) ], index=[row]) for (row,x) in df.iterrows() ])
Out[45]:
ID#1 (2, 4, 7, 9)
ID#2 (3, 5, 7, 9)
ID#3 (1, 5, 7, 8)
ID#4 (2, 4, 7, 9)
ID#5 (1, 5, 7, 8)
ID#6 (3, 5, 7, 9)
dtype: object
创建一个框架,每个 1 位置都有一列
In [46]: DataFrame(dict([ (row,x[x.astype(bool)].index.tolist()) for (row,x) in df.iterrows() ])).T
Out[46]:
0 1 2 3
ID#1 2 4 7 9
ID#2 3 5 7 9
ID#3 1 5 7 8
ID#4 2 4 7 9
ID#5 1 5 7 8
ID#6 3 5 7 9