发现几个小函数,在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
数据预览:

1. 函数replace()
- 不指定字段、默认替换dataframe对象所有字段的元素值
新建一个字典,key存储待替换的元素,value存储替换后的值
newcolors = {'rosso':'red'
,'verde':'green'}
frame1.replace(newcolors)
将字典作为replace()的传入参数,将所有元素为’rosso’替换为’red’, ‘verde’替换为’green’,结果如下。

- 限定字段,只替换目标列
frame1.replace({'color':['white','red']},'myDefineColor')
如下,只对字段color中的元素值有更改,color2不做修改。

2. 函数rename()
- 默认重命名索引名称
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)

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。

小结
留意函数在默认使用时的操作对象是索引还是列、影响范围-是对某列还是整个dataframe对象,不至于误.
本文介绍了Pandas中用于更新和映射DataFrame对象的replace、rename和map函数。通过实例展示了如何使用replace替换特定值,限定替换范围;如何用rename重命名索引和列名;以及如何利用map根据指定列映射新增属性。理解这些函数的不同作用可以帮助更精确地操作DataFrame。

599

被折叠的 条评论
为什么被折叠?



