2014-01-23 284 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