概述
data = DataFrame({‘food’:[‘bacon’,’pull_pork’,’bacon’,’Pastrami’,’corned beef’,’Bacon’,’pastrami’,’honey ham’,’novs lox’],
‘ounces’:[4,3,12,6,7.5,8,3,5,6]})
print(data)
meat_to_animal = {
‘bacon’:’pig’,
‘pulled pork’:’pig’,
‘pastrami’:’cow’,
‘corned beef’:’cow’,
‘honey ham’:’pig’,
‘nova lox’:’salmon’
}
print(meat_to_animal)
data[‘animal’] = data[‘food’].map(str.lower).map(meat_to_animal)
print(data)
以上用的是映射的方式,我们也可以定义一个函数import pandas as pd
from pandas import *
import numpy as np
data = DataFrame({‘food’:[‘bacon’,’pulled pork’,’bacon’,’Pastrami’,’corned beef’,’Bacon’,’pastrami’,’honey ham’,’nova lox’],
‘ounces’:[4,3,12,6,7.5,8,3,5,6]})
print(data)
meat_to_animal = {
‘bacon’:’pig’,
‘pulled pork’:’pig’,
‘pastrami’:’cow’,
‘corned beef’:’cow’,
‘honey ham’:’pig’,
‘nova lox’:’salmon’
}
result = data[‘food’].map(lambda x:meat_to_animal[x.lower()])
print(data)
最后
以上就是虚拟御姐为你收集整理的pandas利用函数或映射进行数据转换的全部内容,希望文章能够帮你解决pandas利用函数或映射进行数据转换所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复