先来看个数据

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 studio - Manifest merger failed with multiple errors, see logs

    今天编译运行的时候遇到了“Error:Execution failed for task ':test:processDebugManifest'.> Manifest merger faile ...

  2. FFmpeg(6)-通过av_find_best_stream()来获取音视流的索引

    也可以通过av_find_best_stream()函数来获取流的索引: 例: audioStream = av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO, -, ...

  3. android笔记---百度地图api应用 (一)

    package com.example.bdtest; import com.baidu.mapapi.MKEvent; import com.baidu.mapapi.MKPlanNode; imp ...

  4. What-are-P-NP-NP-complete-and-NP-hard

    https://www.amazon.com/Computational-Complexity-Approach-Sanjeev-Arora/dp/0521424267 http://theory.c ...

  5. Pycharm 2017.1 激活服务器

    最近发现pycharm激活异常困难 原来的激活码 都不能用了 so 根据网上 教程 自己建了激活服务器 尝试可用服务器 20170504 测试发现 给需要域名 http://www.05nb.com: ...

  6. vue中的filters的用法

    1.效果 金额保留两位小数,并加上单位元 2.index.html <!DOCTYPE html> <html lang="en"> <head> ...

  7. Oracle XQuery 过滤XML查询SQL

    Oralce 支持SQL XQuery查询 一个简单示例: SELECT XMLQuery('for $i in /Videogame return $i/Type' passing by value ...

  8. WebService 获取当前URL

    private string pageRoot = string.Empty; public virtual string PortalRoot { get { if (pageRoot == nul ...

  9. 查看chekpoit文件

    使用tf.train.Saver()保存到checkpoint文件,我们可以用tensorflow查看. # import the inspect_checkpoint library from te ...

  10. Oracle用户密码过期的处理方法

    受影响版本:Oracle11g以上版本.   导致密码消失的原因:Oracle 11g中默认的DEFAULT概要文件中口令有效期PASSWORD_LIFE_TIME默认值为180天.   当以客户端登 ...