python-3.x - 如何在数据名声python中获取最大值的列名?
问题描述
我想获取每行最大值的列名。
S1 S2 S3 S4
Con1 -0.166277 0.329279 5.4941 3.6587
Con2 -0.015557 0.063506 6.5012 -2.6939
Con3 -0.230677 0.525414 7.2712 8.8743
Con4 -0.155739 0.335635 -6.2533 -4.6159
当我使用 df.idxmax(axis=1) 时,它如下所示。
Con1 S1
Con2 S1
Con3 S4
Con4 S2
maxdf = df.idxmax(axis=1)
预期结果:
S1: {Con1,Con2,}
S2: {Con4}
S3: {}
S4: {Con3}
解决方案
创建DataFrame
者Series.reset_index
并聚合set
s,最后添加缺失值Series.reindex
:
maxdf = df.idxmax(axis=1)
print (maxdf)
Con1 S3
Con2 S3
Con3 S4
Con4 S2
dtype: object
s = maxdf.reset_index().groupby(0)['index'].apply(set).reindex(df.columns, fill_value={})
print (s)
S1 {}
S2 {Con4}
S3 {Con2, Con1}
S4 {Con3}
Name: index, dtype: object
如果想要在输出中使用列表:
s = maxdf.reset_index().groupby(0)['index'].apply(list).reindex(df.columns, fill_value=[])
print (s)
S1 []
S2 [Con4]
S3 [Con1, Con2]
S4 [Con3]
Name: index, dtype: object