我有一个Pandas数据帧,如下所示。如何将round
系列下的square
和shape
值合并为other
? (在R术语中,我想将round
因子的square
和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
答案 0 :(得分:2)
df.loc[df['shape'].isin(['round', 'square']), 'shape'] = 'other'
(在@ TomAugspurger的建议之后编辑)