以下是采用不同数据结构的信息:
In [8]: df = pd.Dataframe({'cat1':[0,3,1], 'cat2':[2,0,1], 'cat3':[2,1,0]})In [9]: dfOut[9]: cat1 cat2 cat30 0 2 21 3 0 12 1 1 0[3 rows x 3 columns]In [10]: rowmax = df.max(axis=1)最大值由True值指示:
In [82]: df.values == rowmax[:,None]Out[82]: array([[False, True, True], [ True, False, False], [ True, True, False]], dtype=bool)
np.where
返回上面的Dataframe为True的索引。
In [84]: np.where(df.values == rowmax[:,None])Out[84]: (array([0, 0, 1, 2, 2]), array([1, 2, 0, 0, 1]))
第一个数组指示的索引值
axis=0,第二个数组指示的索引值
axis=1。每个数组中有5个值,因为有五个位置为True。
您可以
itertools.groupby用来构建发布的列表列表,尽管鉴于上述数据结构,也许您不需要这样做:
In [46]: import itertools as ITIn [47]: import operatorIn [48]: idx = np.where(df.values == rowmax[:,None])In [49]: groups = IT.groupby(zip(*idx), key=operator.itemgetter(0))In [50]: [[df.columns[j] for i, j in grp] for k, grp in groups]Out[50]: [['cat1', 'cat1'], ['cat2'], ['cat3', 'cat3']]



