先来看个数据

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)的更多相关文章

  1. python内置函数lambda、filter、map、reduce

    lambda匿名函数 1.lambda只是一个表达式,函数体比def简单多. 2.lambda的主体是一个表达式,而不是一个代码块.仅仅能在lambda表达式中封装有限的逻辑进去 3.lambda函数 ...

  2. Python之路(第七篇)Python作用域、匿名函数、函数式编程、map函数、filter函数、reduce函数

    一.作用域 return 可以返回任意值例子 def test1(): print("test1") def test(): print("test") ret ...

  3. Python3中高阶函数lambda,filter,map,reduce,zip的详细用法

    在Python里有五大高阶函数,他们分别是lambda()匿名函数,filter()筛选函数,map()函数,reduce()函数,zip()函数.下面就让我们来详细的了解一下这五种函数的具体用法吧. ...

  4. Python之路Python作用域、匿名函数、函数式编程、map函数、filter函数、reduce函数

    Python之路Python作用域.匿名函数.函数式编程.map函数.filter函数.reduce函数 一.作用域 return 可以返回任意值例子 def test1(): print(" ...

  5. python递归函数、二分法、匿名函数、(sorted、map、filter内置函数应用)

    #函数递归是一种特殊的函数嵌套调用,在调用一个函数的过程中,又直接或间接的调用该函数本身递归必须要有两个明确的阶段: 递推:一层一层递归调用下去,强调每进入下一层递归问题的规模都必须有所减少 回溯:递 ...

  6. flask之路径与函数的映射

    一:运行报错 OSError: [Errno 98] Address already in use:5000端口可能被占 lsof -i:端口号  查看端口被那个进程使用,结果是python3.5 k ...

  7. 利用函数索引优化<>

    SQL> select count(*),ID from test_2 group by id; COUNT(*) ID ---------- ---------- 131072 1 11796 ...

  8. Python中利用函数装饰器实现备忘功能

    Python中利用函数装饰器实现备忘功能 这篇文章主要介绍了Python中利用函数装饰器实现备忘功能,同时还降到了利用装饰器来检查函数的递归.确保参数传递的正确,需要的朋友可以参考下   " ...

  9. 如何利用Grunt生成对应的Source Map文件,线上代码压缩使用chrome浏览器便于调式

    如何利用Grunt生成对应的Source Map文件,线上代码压缩使用chrome浏览器便于调式 首先我们来说说为何要生成sourceMap文件呢?简单的说,sourceMap是为了压缩后的代码调式提 ...

随机推荐

  1. 发布Web应用程序时发生的“xx.aspx.cs文件不存在”错误

    (注意:这里说的Web应用程序并不是Web网站) 在VS里调试.IIS里浏览含.CS源码的项目都是没有问题的.但是发布后,所有的.CS文件都被编译到bin文件夹里去了.在IIS里浏览,发生“分析器错误 ...

  2. # file Python-3.4.7.tar.xz Python-3.4.7.tar.xz: XZ compressed data

    # file Python-3.4.7.tar.xz Python-3.4.7.tar.xz: XZ compressed data # xz -d Python-3.4.7.tar.xz # ls ...

  3. android: getDimension, getDimensionPixelOffset 和getDimensionPixelSize 区别

    ◆结论: getDimension 获取某个dimen的值,如果是dp或sp的单位,将其乘以density,如果是px,则不乘   返回float getDimensionPixelOffset 获取 ...

  4. angular的uiRouter服务学习(2)

    本篇接着上一篇 angular的uiRouter服务学习(1) 继续讲解uiRouter的用法 本篇主要讲解uiRouter的嵌套状态&嵌套视图 嵌套状态的方法: 状态和状态之间可以互相嵌套, ...

  5. 微信小程序启动过程分析

    1.微信客户端在打开小程序之前,会把整个小程序的代码包下载到本地. 2.紧接着通过 app.json 的 pages 字段就可以知道你当前小程序的所有页面路径: { "pages" ...

  6. javascript基础拾遗(三)

    1.map数组映射操作 function add(x) { return x+1 } var nums = [1,3,5,7,9] result = nums.map(add) console.log ...

  7. iOS-通讯录(无界面)

    通讯录(无界面) #import "AppDelegate.h" #import <AddressBook/AddressBook.h> @interface AppD ...

  8. THP Transparent HugePages 相关知识与关闭【转】

    最近遇到个LINUX系统内存比较大,未开 HugePages,业务有变化导致ORACLE连接数剧增至上千个,PageTables达到上百G,导致内存不足系统HANG住的案例. 因此需要开启 HugeP ...

  9. mysql 添加外键时 error 150 问题总汇

    当你试图在mysql中创建一个外键的时候,这个出错会经常发生,这是非常令人沮丧的.像这种不能创建一个.frm 文件的报错好像暗示着操作系统的文件的权限错误或者其它原因,但实际上,这些都不是的,事实上, ...

  10. C#学习笔记(14)——C# 使用IComparer自定义List类的排序方案

    说明(2017-7-17 21:34:59): 原文:https://my.oschina.net/Tsybius2014/blog/298702?p=1 另一篇比较好的:https://wenku. ...