准备数据样例:
frame1 = pd.DataFrame({'item':['ball','mug','pen','pencil','ashtray'],
'color':['white','rosso','verde','black','yellow'],
'price':[5,9,2,3,1],
'color2':['white','rosso','rosso','verde','yellow']})
frame1
newcolors = {'rosso':'red'
,'verde':'green'}
frame1.replace(newcolors)
将字典作为replace()的传入参数,将所有元素为’rosso’替换为’red’, ‘verde’替换为’green’,结果如下。
frame1.replace({'color':['white','red']},'myDefineColor')
如下,只对字段color中的元素值有更改,color2不做修改。
reindex = {0:'first',
1:'second',
2:'third',
3:'four',
5:'five'}
frame1.rename(reindex)
recolumn = {'item':'t_item',
'color':'t_color'}
frame2.rename(columns = recolumn)
用来对已有pandas对象按照指定列关联并新增属性,类似于数据库SQL的中join操作后,再添加新的字段。
frame2 = pd.DataFrame({'item':['ball','mug','pen','pencil','ashtray'],
'color':['white','red','green','black','yellow']})
price = {'ball':3,
'mug':8,
'bottle':9}
frame2['price'] = frame2['item'].map(price)
frame2
对frame2中的item字段实现map()操作,新增price字段。若字典Price中的key值与item列中的元素值相等,则取字典中相应的value,否则,默认为NULL。
留意函数在默认使用时的操作对象是索引还是列、影响范围-是对某列还是整个dataframe对象,不至于误.