Pandas中利用函数或者映射进行数据转换---你想要的都在这~

Pandas中利用函数或者映射进行数据转换

  • 我们先创建一个dataframe
data = pd.DataFrame({'food': ['Apple', 'banana', 'orange','apple','Mango', 'tomato'],
                    'price': [4, 3, 3.5, 6, 12,3]})
data


	food	price
0	Apple	4.0
1	banana	3.0
2	orange	3.5
3	apple	6.0
4	Mango	12.0
5	tomato	3.0

接下来我们想将水果归为一类,蔬菜归为一类,观察数据发现,里面不仅有大写还有小写,所以我们先处理这一个情况。

# 值小写 
# 利用str中的lower()函数
low = data['food'].str.lower()
low

0     apple
1    banana
2    orange
3     apple
4     mango
5    tomato
Name: food, dtype: object

接下来,我们利用字典创建一个分类。

m= {'apple':'fruit',
       'banana':'fruit',
       'orange':'fruit',
       'mango':'fruit',
       'tomato':'vagetable'}
# 增加一个列 然后利用map函数将数据与我们的字典对应 
# 先找如果是apple 就归为fruit 其他同理
data['class'] = low.map(meat)
data

	food	price	class
0	Apple	4.0		fruit
1	banana	3.0		fruit
2	orange	3.5		fruit
3	apple	6.0		fruit
4	Mango	12.0	fruit
5	tomato	3.0	vagetable

# 或者利用函数
# 同样是现在字典中找键然后找到了就归为一类
data['class1'] = data['food'].map(lambda x:m[x.lower()])
data

	food	price	class	class1
0	Apple	4.0	fruit	fruit
1	banana	3.0	fruit	fruit
2	orange	3.5	fruit	fruit
3	apple	6.0	fruit	fruit
4	Mango	12.0	fruit	fruit
5	tomato	3.0	vagetable	vagetable

总结:我们可以用map对数据进行映射然后进行相应的数据转换

发布了21 篇原创文章 · 获赞 12 · 访问量 439

猜你喜欢

转载自blog.csdn.net/weixin_44984627/article/details/104822290