先来看个数据

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. android源码编译-Mac 10.11 xcode5.1.1

    第一步: 参考官网:创建一个dmg,大小80g,这个要尽量大一点,40g感觉不够用:http://source.android.com/source/initializing.html 第二步:下载a ...

  2. AWS产品目录

    计算 Amazon EC2:弹性虚拟机 AWS Batch:批处理计算 Amazon ECR:Docker容器管理 Amazon ECS:高度可扩展的快速容器管理服务 Amazon EKS:在AWS上 ...

  3. Android调用Webservice发送文件

    一服务器端C#这里有三个上传方法1.uploadFile( byte []bs, String fileName); PC机操作是没有问题2. uploadImage(String filename, ...

  4. 【转】Pycharm创建py文件时自定义头部模板

    File->settings->Editor->File and Code Templates->Python Script #!/usr/bin/env python # - ...

  5. Python排序dict之list数组

    两种办法: 其一lambda表达式: ctx['data'] = sorted(ctx['data'], key=lambda k: k['asrtime'], reverse=True) 其二利用o ...

  6. LeetCode: Palindrome Partitioning 解题报告

    Given a string s, partition s such that every substring of the partition is a palindrome. Return all ...

  7. Nginx缓存功能、防盗链、URL重写

    nginx做为反向代理时,能够将来自upstream的响应缓存至本地,并在后续的客户端请求同样内容时直接从本地构造响应报文. nginx的缓存数据结构: 共享内存:存储键和缓存对象元数据 磁盘空间:存 ...

  8. java 多线程 30: 多线程组件之 CyclicBarrier

    CyclicBarrier 接着讲多线程下的其他组件,第一个要讲的就是CyclicBarrier.CyclicBarrier从字面理解是指循环屏障,它可以协同多个线程,让多个线程在这个屏障前等待,直到 ...

  9. Spark Shuffle 中 JVM 内存使用及配置内幕详情

      本课主题 JVM 內存使用架构剖析 Spark 1.6.x 和 Spark 2.x 的 JVM 剖析 Spark 1.6.x 以前 on Yarn 计算内存使用案例 Spark Unified M ...

  10. 【Unity笔记】根骨骼动画/运动(Root Motion)

    根骨骼动画:当动画中角色发生位移后,动作坐标原点跟随角色移动.例如一个向前跳跃的动画,如果在场景中重复该动画,能够看到角色一路往前跳跃,位置一直在前进.适用于有位移的放技能动作等. 非根骨骼动画:当动 ...