我从两个pandas列创建了一个二进制矩阵
DF:
ID_2 ID_1 1111 1 22222 2 33333 3 33333 4 44444 5 55555 6 55555 7 66666 8 66666 9 77777 10 77777 11 77777 12
使用:
A = pd.get_dummies(df.set_index('ID_1')['ID_2'].astype(str)).max(level=0) print (A)
这将创建一个矩阵:
22222 33333 44444 55555 66666 77777 11111 ID_2 1 0 0 0 0 0 0 1 2 1 0 0 0 0 0 0 3 0 1 0 0 0 0 0 4 0 1 0 0 0 0 0 5 0 0 1 0 0 0 0
…
一切正常-除了id_1的第一个唯一值被放在最后一列。我需要将值的顺序保留为id_2中的顺序。
如果要重新排序列,我认为您需要:
A = A.reindex_axis(['11111'] + list(A.columns[:-1]), axis=1)
你可以这样做:
from collections import OrderedDict cols = list(OrderedDict.fromkeys(list(df['ID_2'].values))) cols = [str(i) for i in cols] A = A.reindex_axis(cols, axis=1)
在这里,您以一种有序的方式(没有重复项)保留列的元素,然后使用它们作为标题