利用函数或映射进行数据转换 (map)
先来看个数据
df = 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(df)

需求, 你想要添加一列表示该肉类食物来源的动物类型。 我们先编写一个肉类到动物的映射:
meat_to_animal = {
"bacon": "pig",
"pulled pork": "pig",
"pastrami": "cow",
"corned beef": "cow",
"honey ham": "pig",
"nova lox": "salmon"
}
Series的map方法可以接受一个函数或含有映射关系的字典型对象, 但是这里有一个小问题, 即有些肉类
的首字母大写了, 而另一些则没有。因此, 我们还需要将各个值转换为小写:
各种方法:
df = 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(df)
meat_to_animal = {
"bacon": "pig",
"pulled pork": "pig",
"pastrami": "cow",
"corned beef": "cow",
"honey ham": "pig",
"nova lox": "salmon"
}
# df['animal'] = df['food'].map(str.lower).map(meat_to_animal)
# print(df)
# df['animal'] = df['food'].map(meat_to_animal)
# print(df)
df1 = df['food'].map(str.lower).map(meat_to_animal)
print(df1)
print("-----------------------")
df3 = df["food"].map(lambda x:meat_to_animal[x.lower()])
print(df3)
print('---------------------') #此方法得到的是key, 不是value了, 特此表明
df2 = df["food"].map(lambda x:x.lower(), meat_to_animal)
print(df2)
还要个方法, 替换值
df = 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(df)
meat_to_animal = {
"bacon": "pig",
"pulled pork": "pig",
"pastrami": "cow",
"corned beef": "cow",
"honey ham": "pig",
"nova lox": "salmon"
}
df['ounces'] = df['food'].map(str.lower).map(meat_to_animal)
print(df)
看源码例子
>>> x
one 1
two 2
three 3 >>> y
1 foo
2 bar
3 baz >>> x.map(y)
one foo
two bar
three baz
还有个na_nation参数, 如果需要看源码
>>> s = pd.Series([1, 2, 3, np.nan])
>>> s2 = s.map(lambda x: 'this is a string {}'.format(x),
na_action=None)
0 this is a string 1.0
1 this is a string 2.0
2 this is a string 3.0
3 this is a string nan
dtype: object
>>> s3 = s.map(lambda x: 'this is a string {}'.format(x),
na_action='ignore')
0 this is a string 1.0
1 this is a string 2.0
2 this is a string 3.0
3 NaN
dtype: object
利用函数或映射进行数据转换 (map)的更多相关文章
- python内置函数lambda、filter、map、reduce
lambda匿名函数 1.lambda只是一个表达式,函数体比def简单多. 2.lambda的主体是一个表达式,而不是一个代码块.仅仅能在lambda表达式中封装有限的逻辑进去 3.lambda函数 ...
- Python之路(第七篇)Python作用域、匿名函数、函数式编程、map函数、filter函数、reduce函数
一.作用域 return 可以返回任意值例子 def test1(): print("test1") def test(): print("test") ret ...
- Python3中高阶函数lambda,filter,map,reduce,zip的详细用法
在Python里有五大高阶函数,他们分别是lambda()匿名函数,filter()筛选函数,map()函数,reduce()函数,zip()函数.下面就让我们来详细的了解一下这五种函数的具体用法吧. ...
- Python之路Python作用域、匿名函数、函数式编程、map函数、filter函数、reduce函数
Python之路Python作用域.匿名函数.函数式编程.map函数.filter函数.reduce函数 一.作用域 return 可以返回任意值例子 def test1(): print(" ...
- python递归函数、二分法、匿名函数、(sorted、map、filter内置函数应用)
#函数递归是一种特殊的函数嵌套调用,在调用一个函数的过程中,又直接或间接的调用该函数本身递归必须要有两个明确的阶段: 递推:一层一层递归调用下去,强调每进入下一层递归问题的规模都必须有所减少 回溯:递 ...
- flask之路径与函数的映射
一:运行报错 OSError: [Errno 98] Address already in use:5000端口可能被占 lsof -i:端口号 查看端口被那个进程使用,结果是python3.5 k ...
- 利用函数索引优化<>
SQL> select count(*),ID from test_2 group by id; COUNT(*) ID ---------- ---------- 131072 1 11796 ...
- Python中利用函数装饰器实现备忘功能
Python中利用函数装饰器实现备忘功能 这篇文章主要介绍了Python中利用函数装饰器实现备忘功能,同时还降到了利用装饰器来检查函数的递归.确保参数传递的正确,需要的朋友可以参考下 " ...
- 如何利用Grunt生成对应的Source Map文件,线上代码压缩使用chrome浏览器便于调式
如何利用Grunt生成对应的Source Map文件,线上代码压缩使用chrome浏览器便于调式 首先我们来说说为何要生成sourceMap文件呢?简单的说,sourceMap是为了压缩后的代码调式提 ...
随机推荐
- 如何将git本地创建的项目推送到github仓库
除了集中式的版本控制系统CVS和SVN外,还有目前世界上最先进的分布式版本控制系统Git,它的创始人是创建了linux的大神 - linus.GitHub网站与2008年开始服役,为开源项目免费提供G ...
- 每日英语:Booming Tech Sector Redraws the Map
China's high-tech companies have made their mark on the nation's economy. Now, with growing cash and ...
- 2017-04-26 ios ipv6那些事(已完美解决)
2017-04-26 ios ipv6那些事(已完美解决) 工作单位性质属于外包公司,每天都有几十的app要提交上传至应用市场,于2017年3月份接到ios工程师反馈 Guideline 2.1 ...
- 4.3之后的PingPong效果实现
旧版本的Unity提供Animation编辑器来编辑物理动画. 在其下方可以设置动画是Loop或者是Pingpong等运动效果. 但是,在4.3之后,Unity的动画系统发生了较大的变化. 相信很多童 ...
- 使用Maven对JAVA程序打包-带主类、带依赖【转】
很多时候,我们需要对编写的程序进行打包,这个时候,我们可以借助一些项目构建工具,如maven, sbt, ant等,这里我使用的是maven. 打包成可执行有主类的jar包(jar包中无依赖) 以下是 ...
- asp.net上传大文件-请求筛选模块被配置为拒绝超过请求内容长度的请求
HTTP错误404.13 - Not Found 请求筛选模块被配置为拒绝超过请求内容长度的请求,原因是Web服务器上的请求筛选被配置为拒绝该请求,因为内容长度超过配置的值(IIS 7 默认文件上传大 ...
- Win7 IIS7 HTTP 错误 404.2 - Not Found解决方法 ISAPI CGI
Win7 +IIS 刚配置的网站,输入网址后报以下错误: 应用程序“PFIZERQUERY”中的服务器错误 Internet Information Services 7.5 错误摘要 HTTP 错误 ...
- iOS概念之KVO(Key-Value Observing)
在一个复杂的,有状态的系统中,当一个对象的状态发生改变,如何通知系统,并对状态改变做出相应的行为是必需考虑的一个问题,在iOS中为这类问题提供了4种解决方法: 1. NSNotifiactaion和N ...
- PHP error_reporting() 函数
实例 规定不同的错误级别报告: <?php // 关闭错误报告 error_reporting(0); // 报告 runtime 错误 error_reporting(E_ERROR | E_ ...
- python read file(f,csv)
import csv def readfile0(): print('test read file') in_file = open('C:\python\demo\LiaoXueFeng\data\ ...