python中pandas数据框使用applymap替换数据的一个例子
代码在Python Console中操作的
要求
data = {'Fruit':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'Weight':[23, 45, 31, 28, 62, 12, 44, 42, 23, 32], 'Taste':['good', 'so so', 'very good', 'awful', 'awful', 'very good', 'good', 'good', 'awful', 'good'], 'Look':['good', 'good', 'so so', 'awful', 'so so', 'very good', 'very good', 'good', 'awful', 'good']}
将上面数据中的“ Taste”和“ Look”中的值从“很好”更改为4-1。如果只有一列,我会写:
'very good': 4, 'good': 3, 'so so': 2, 'awful': 1
整理
我们使用pandas整理一下原始数据,看上去更清晰
data = {'Fruit':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'Weight':[23, 45, 31, 28, 62, 12, 44, 42, 23, 32], 'Taste':['good', 'so so', 'very good', 'awful', 'awful', 'very good', 'good', 'good', 'awful', 'good'], 'Look':['good', 'good', 'so so', 'awful', 'so so', 'very good', 'very good', 'good', 'awful', 'good']} import pandas as pd data_=pd.DataFrame(data) data_ Fruit Weight Taste Look 0 1 23 good good 1 2 45 so so good 2 3 31 very good so so 3 4 28 awful awful 4 5 62 awful so so 5 6 12 very good very good 6 7 44 good very good 7 8 42 good good 8 9 23 awful awful 9 10 32 good good
解决
完整的代码如下
data = {'Fruit':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'Weight':[23, 45, 31, 28, 62, 12, 44, 42, 23, 32], 'Taste':['good', 'so so', 'very good', 'awful', 'awful', 'very good', 'good', 'good', 'awful', 'good'], 'Look':['good', 'good', 'so so', 'awful', 'so so', 'very good', 'very good', 'good', 'awful', 'good']} import pandas as pd data_=pd.DataFrame(data) data_ Fruit Weight Taste Look 0 1 23 good good 1 2 45 so so good 2 3 31 very good so so 3 4 28 awful awful 4 5 62 awful so so 5 6 12 very good very good 6 7 44 good very good 7 8 42 good good 8 9 23 awful awful 9 10 32 good good d = {'very good': 4, 'good': 3, 'so so': 2, 'awful': 1} data_[["Taste","Look"]]=data_[["Taste","Look"]].applymap(d.get) data_ Fruit Weight Taste Look 0 1 23 3 3 1 2 45 2 3 2 3 31 4 2 3 4 28 1 1 4 5 62 1 2 5 6 12 4 4 6 7 44 3 4 7 8 42 3 3 8 9 23 1 1 9 10 32 3 3
运营不易,
感谢支持!
我的微信
我的微信公众号
我的微信公众号扫一扫
我的公众号