L2-pandas中的replace、rename和map函数

发现几个小函数,在pandas中用来对dataframe对象进行更新与映射操作,试用并分享如下。

准备数据样例:

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

数据预览:
L2-pandas中的replace、rename和map函数_第1张图片

1. 函数replace()

  • 不指定字段、默认替换dataframe对象所有字段的元素值
    新建一个字典,key存储待替换的元素,value存储替换后的值
newcolors = {'rosso':'red'
            ,'verde':'green'}
frame1.replace(newcolors)

将字典作为replace()的传入参数,将所有元素为’rosso’替换为’red’, ‘verde’替换为’green’,结果如下。
L2-pandas中的replace、rename和map函数_第2张图片

  • 限定字段,只替换目标列
frame1.replace({'color':['white','red']},'myDefineColor')

如下,只对字段color中的元素值有更改,color2不做修改。
L2-pandas中的replace、rename和map函数_第3张图片

2. 函数rename()

  • 默认重命名索引名称
 reindex = {0:'first',
          1:'second',
          2:'third',
          3:'four',
          5:'five'}
frame1.rename(reindex)

L2-pandas中的replace、rename和map函数_第4张图片

  • 指定参数重命名字段名称
recolumn = {'item':'t_item',
          'color':'t_color'}
frame2.rename(columns = recolumn)

L2-pandas中的replace、rename和map函数_第5张图片

3.map() 映射

用来对已有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。
L2-pandas中的replace、rename和map函数_第6张图片

小结

留意函数在默认使用时的操作对象是索引还是列、影响范围-是对某列还是整个dataframe对象,不至于误.

你可能感兴趣的:(Python实战)