2014-01-23 279 views
0

我有一個熊貓數據框如下。我怎樣才能將roundsquare的值合併爲shape系列作爲other? (在讀的術語,我想將roundsquare水平shape因素合併成標other一個新的水平。)熊貓:合併系列值

df = pd.DataFrame({'id' : range(1,9), 
        'code' : ['one', 'one', 'two', 'three', 
           'two', 'three', 'one', 'two'], 
        'shape': ['round', 'triangular', 'triangular','triangular','square', 
             'triangular','round','triangular'], 
        'amount' : np.random.randn(8)}, columns= ['id','code', 'shape', 'amount']) 
df 
    id code  shape amount 
0 1 one  round -0.187789 
1 2 one triangular 1.286208 
2 3 two triangular 0.171734 
3 4 three triangular 0.394471 
4 5 two  square -0.009613 
5 6 three triangular 0.413767 
6 7 one  round 1.264730 
7 8 two triangular 0.516499 

回答

2

這是什麼意思?

df.loc[df['shape'].isin(['round', 'square']), 'shape'] = 'other' 

+0

是(在@ TomAugspurger的建議編輯),我相信如此。熊貓系列沒有水平,所以我不必擔心下降水平('圓形和'方形),對吧? – Rhubarb

+0

他們是字符串,所以我不認爲你應該擔心 – mkln

+1

您可能想要將其更改爲'df.loc [df ['shape']。isin(['round','square']),'shape' ] ='其他',以避免複製錯誤的可能設置。這裏似乎不成問題,但最好避免鏈接分配。 – TomAugspurger