遍历大熊猫行并获取值组?

时间:2020-03-16 19:12:24

标签: python pandas

我有一个Df,看起来像:

marker | 0 1 2 3
________________
A      | + - + -
B      | - - + -
C      | - + - -

,我想遍历各列并获取其中有+的行的名称,即将所有+行分组。

我试图通过以下方式做到这一点:

lis = []

for n in list(range(0,3)):
    cli = Df[n].tolist()
    for x,m in zip(cli,markers): # markers is a list of the row names ['A','B','C']
        cl_li = []
        if x == '+':
            mset = m+x
            cl_li.append(mset)
        else:
            continue
        lis.append(cl_li)

print (lis)

但是我将每个行名作为其名称中的自己的子列表,而我想要这样的东西:

newdf = 
____________
0   |  A+
1   |  C+
2   |  A+B+

#n.b group 3 not included

2 个答案:

答案 0 :(得分:1)

尝试在布尔矩阵上使用applyjoin

(df == '+').apply(lambda x: '+'.join(x.index[x])+'+').to_frame()

输出:

           0
marker      
0         A+
1         C+
2       A+B+

或者,使用dot和布尔矩阵:

(df.index.to_series()+'+').dot((df=='+'))

输出:

           0
marker      
0         A+
1         C+
2       A+B+

答案 1 :(得分:1)

我的建议是使用比您更多的pandasonic解决方案。

将lambda函数应用于每列:

result = df.apply(lambda col: ''.join(col[col == '+'].index + '+'))

要从结果中删除空项目,请运行:

result = result[result != '']

结果是:

0      A+
1      C+
2    A+B+
dtype: object

如果希望将结果作为DataFrame(而不是 Series ),请运行:

result = result[result != ''].to_frame()