2017-04-02 102 views
4

我有一個數據幀熊貓:在所有列

graph 0  1  2  3  4 
1  blue blue blue blue blue 
2  blue blue blue blue blue 
3  blue red  blue blue red 
4  red  blue red  red  blue 
5  red  red  blue red  red 
6  blue blue blue blue blue 

我需要讓每一個串/行的值「藍色」的計算一定的價值。
所需的輸出:

graph result 
1  5 
2  5 
3  3 
4  2 
5  1 
6  5 

我嘗試用

(df['0', '1', '2', '3', '4']).applymap(lambda x: str.count(x, 'blue')) 

做,但它返回

KeyError: ('0', '1', '2', '3', '4') 

回答

3
In [35]: df.set_index('graph').eq('blue').sum(1).reset_index(name='result') 
Out[35]: 
    graph result 
0  1  5 
1  2  5 
2  3  3 
3  4  2 
4  5  1 
5  6  5 
1

隨着numpy彎曲。如果您可靠地知道列的位置,則可以從頭開始重建,即列0

v = df.values 
pd.DataFrame(dict(graph=v[:, 0], result=(df.values[:, 1:] == 'blue').sum(1))) 

    graph result 
0  1  5 
1  2  5 
2  3  3 
3  4  2 
4  5  1 
5  6  5 

幼稚時間測試
enter image description here