簡體   English   中英

迭代熊貓行並獲取值組?

[英]Iterate over pandas rows and get groups of values?

我有一個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

嘗試在布爾矩陣上使用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+

我的提議是使用比你更多的 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM