按索引值迭代Dataframe并查找max

时间:2017-12-06 10:04:21

标签: python-2.7 pandas

我需要根据其索引迭代df行。我需要在列p1中找到最大值并将其填入输出数据帧(以及最大值p1),对于列p2也是如此。在我的行索引的每个范围内(sub_1_ica_1 ---> sub_1_ica_n),必须只有一个1和一个2,我需要用零填充剩余的。这就是我需要按范围进行操作范围的原因。

enter image description here

我试图拆分索引名称并为每个主题创建一个计数器来迭代行,但我觉得我的方法错了!

    from collections import Counter
    a = df.id.tolist()
    indlist = []
    for x in a:
    i = x.split('_')
    b = int(i[1])
    indlist.insert(-1,b)
    c=Counter(indlist)
    keyInd = c.keys()

有什么想法吗?

编辑:根据Jerazel的例子,我想要的输出看起来像这样。 首先,我找到p1和p2列的最大值,它们将在新的df中转换为1和2,其余的字段将为零

enter image description here

1 个答案:

答案 0 :(得分:1)

我认为您需要使用numpy.argmax max,如果需要列名称使用idxmax

idx = ['sub_1_ICA_0','sub_1_ICA_1','sub_1_ICA_2','sub_2_ICA_0','sub_2_ICA_1','sub_2_ICA_2']
df = pd.DataFrame({'p0':[7,8,9,4,2,3],
                   'p1':[1,3,5,7,1,0],
                   'p2':[5,9,6,1,2,4]}, index=idx)

print (df)

cols = ['p0','p1','p2']
df['a'] = df[cols].values.argmax(axis=1)
df['b'] = df[cols].max(axis=1)
df['c'] = df[cols].idxmax(axis=1)
print (df)
             p0  p1  p2  a  b   c
sub_1_ICA_0   7   1   5  0  7  p0
sub_1_ICA_1   8   3   9  2  9  p2
sub_1_ICA_2   9   5   6  0  9  p0
sub_2_ICA_0   4   7   1  1  7  p1
sub_2_ICA_1   2   1   2  0  2  p0
sub_2_ICA_2   3   0   4  2  4  p2