使用 pandas 处理数据时,遍历和并行处理是比较常见的操作了本文总结了几种不同样式的操作和并行处理方法。

1. 准备示例数据

import pandas as pd
import numpy as np df = pd.DataFrame(np.random.randint(40, 100, (5, 10)), columns=[f's{i}' for i in range(10)], index=['john', 'bob', 'mike', 'bill', 'lisa'])
df['is_passed'] = df.s9.map(lambda x: True if x > 60 else False)

df 输出:

      s0  s1  s2  s3  s4  s5  s6  s7  s8  s9  is_passed
john 56 70 85 91 92 80 63 81 45 57 False
bob 99 93 80 42 91 81 53 75 61 78 True
mike 76 92 76 80 57 98 94 79 87 94 True
bill 81 83 92 91 51 55 40 77 96 90 True
lisa 85 82 56 57 54 56 49 43 99 51 False

2. 遍历

pandas 中,共有三种遍历数据的方法,分别是:

2.1. iterrows

按行遍历,将 DataFrame 的每一行迭代为 (index, Series) 对,可以通过 row[name]row.name 对元素进行访问。

>>> for index, row in df.iterrows():
... print(row['s0']) # 也可使用 row.s0 56
99
76
81
85

2.2. itertuples

按行遍历,将 DataFrame 的每一行迭代为命名元祖,可以通过 row.name 对元素进行访问,比 iterrows 效率高。

>>> for row in df.itertuples():
... print(row.s0) 56
99
76
81
85

2.3. iteritems

按列遍历,将 DataFrame 的每一列迭代为 (列名, Series) 对,可以通过 row[index] 对元素进行访问。

>>> for index, row in df.iteritems():
... print(row[0]) 56
70
85
91
92
80
63
81
45
57
False

3. 并行处理

3.1. map 方法

类似 Python 内建的 map() 方法,pandas 中的 map() 方法将函数、字典索引或是一些需要接受单个输入值的特别的对象与对应的单个列的每一个元素建立联系并串行得到结果。map() 还有一个参数 na_action,类似 R 中的 na.action,取值为 None(默认) 或 ingore,用于控制遇到缺失值的处理方式,设置为 ingore 时串行运算过程中将忽略 Nan 值原样返回。

比如这里将 is_passed 列中的 True 换为 1False 换位 0,可以有下面几种实现方式:

3.1.1. 字典映射

>>> # 定义映射字典
... score_map = {True: 1, False: 0} >>> # 利用 map() 方法得到对应 mike 列的映射列
... df.is_passed.map(score_map) john 0
bob 1
mike 1
bill 1
lisa 0
Name: is_passed, dtype: int64

3.1.2. lambda 函数

>>> # 如同创建该列时的那样
... df.is_passed.map(lambda x: 1 if x else 0) john 0
bob 1
mike 1
bill 1
lisa 0
Name: is_passed, dtype: int64

3.1.3. 常规函数

>>> def bool_to_num(x):
... return 1 if x else 0 >>> df.is_passed.map(bool_to_num)

3.1.4. 特殊对象

一些接收单个输入值且有输出的对象也可以用map()方法来处理:

>>> df.is_passed.map('is passed: {}'.format)

john    is passed: False
bob is passed: True
mike is passed: True
bill is passed: True
lisa is passed: False
Name: is_passed, dtype: object

3.2. apply 方法

apply() 使用方式跟 map() 很像,主要传入的主要参数都是接受输入返回输出,但相较于 map() 针对单列 Series 进行处理,一条 apply() 语句可以对单列或多列进行运算,覆盖非常多的使用场景,下面分别介绍:

3.2.1. 单列数据

传入 lambda 函数:

df.is_passed.apply(lambda x: 1 if x else 0)

3.2.2. 输入多列数据

>>> def gen_describe(s9, is_passed):
... return f"s9's score is {s9}, so {'passed' if is_passed else 'failed'}" >>> df.apply(lambda r: gen_describe(r['s9'], r['is_passed']), axis=1) john s9's score is 57, so failed
bob s9's score is 78, so passed
mike s9's score is 94, so passed
bill s9's score is 90, so passed
lisa s9's score is 51, so failed
dtype: object

3.2.3. 输出多列数据

>>> df.apply(lambda row: (row['s9'], row['s8']), axis=1)

john    (57, 45)
bob (78, 61)
mike (94, 87)
bill (90, 96)
lisa (51, 99)
dtype: object

3.3. applymap 方法

applymap 是与 map 方法相对应的专属于 DataFrame 对象的方法,类似 map 方法传入函数、字典等,传入对应的输出结果,

不同的是 applymap 将传入的函数等作用于整个数据框中每一个位置的元素,比如将 df 中的所有小于 50 的全部改为 50

>>> def at_least_get_50(x):
... if isinstance(x, int) and x < 50:
... return 50
... return x >>> df.applymap(at_least_get_50) s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 is_passed
john 56 70 85 91 92 80 63 81 50 57 False
bob 99 93 80 50 91 81 53 75 61 78 True
mike 76 92 76 80 57 98 94 79 87 94 True
bill 81 83 92 91 51 55 50 77 96 90 True
lisa 85 82 56 57 54 56 50 50 99 51 False

附:结合 tqdm 给 apply 过程添加进度条

jupyter 中并行处理较大数据量的时候,往往执行后就只能干等着报错或者执行完了,使用 tqdm 可以查看数据实时处理进度,使用前需使用 pip install tqdm 安装该包。使用示例如下:

from tqdm import tqdm

def gen_describe(s9, is_passed):
return f"s9's score is {s9}, so {'passed' if is_passed else 'failed'}" #启动对紧跟着的 apply 过程的监视
tqdm.pandas(desc='apply')
df.progress_apply(lambda r: gen_describe(r['s9'], r['is_passed']), axis=1)

参考

  1. (数据科学学习手札69)详解pandas中的map、apply、applymap、groupby、agg

Pandas 中的遍历与并行处理的更多相关文章

  1. pandas中的遍历方式速度对比

    对一个20667行的xlsx文件进行遍历测试 import pandas as pd # 定义一个计算执行时间的函数作装饰器,传入参数为装饰的函数或方法 def print_execute_time( ...

  2. pandas中的分组技术

    目录 1  分组操作 1.1  按照列进行分组 1.2  按照字典进行分组 1.3  根据函数进行分组 1.4  按照list组合 1.5  按照索引级别进行分组 2  分组运算 2.1  agg 2 ...

  3. (数据科学学习手札69)详解pandas中的map、apply、applymap、groupby、agg

    *从本篇开始所有文章的数据和代码都已上传至我的github仓库:https://github.com/CNFeffery/DataScienceStudyNotes 一.简介 pandas提供了很多方 ...

  4. pandas中的axis参数(看其他人的博客中产生的疑问点,用自己的话解析出来)

    axis有两个值:axis=0或者axis=1 看到很多资料都不太理解,把我个人理解说一下: 下面这张图,在很多资料中都看到了,我只能说先死记住 axis=0,代表跨行(注意看这张图的axis=0的箭 ...

  5. [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal 由先序和中序遍历建立二叉树

    Given preorder and inorder traversal of a tree, construct the binary tree. Note:You may assume that ...

  6. [LeetCode] Binary Tree Inorder Traversal 二叉树的中序遍历

    Given a binary tree, return the inorder traversal of its nodes' values. For example:Given binary tre ...

  7. nyoj202_红黑树_中序遍历

    红黑树 时间限制:3000 ms  |  内存限制:65535 KB 难度:3   描述 什么是红黑树呢?顾名思义,跟枣树类似,红黑树是一种叶子是黑色果子是红色的树... 当然,这个是我说的... & ...

  8. DS实验题 Order 已知父节点和中序遍历求前、后序

    题目: 思路: 这题是比较典型的树的遍历问题,思路就是将中序遍历作为位置的判断依据,假设有个节点A和它的父亲Afa,那么如果A和Afa的顺序在中序遍历中是先A后Afa,则A是Afa的左儿子,否则是右儿 ...

  9. YTU 2346: 中序遍历二叉树

    原文链接:https://www.dreamwings.cn/ytu2346/2606.html 2346: 中序遍历二叉树 时间限制: 1 Sec  内存限制: 128 MB 提交: 12  解决: ...

随机推荐

  1. CentOS下删除物理磁盘,删除LVM

    1.删除 dmsetup remove LV_name 2.vgreduce VG_name --removemissing 3.vgremove VG_name 4.pvremove disk

  2. kvm-virtualization – 删除“孤儿”libvirt快照

    原文链接:https://codeday.me/bug/20181110/371346.html 创建快照: virsh snapshot-create-as --domain prod snap - ...

  3. 算法-搜索(6)B树

    B树是平衡的m路搜索树. 根结点至少两个子女,根结点以外的非失败结点至少⌈m/2⌉个子女,所有失败结点都在h+1层. 第h层至少2⌈m/2⌉h-1个结点,因此失败结点数n+1≥2⌈m/2⌉h-1个. ...

  4. 在Unity中检测死循环和卡死

    当游戏在手机/模拟器上卡死,logcat没有日志输出,也没有卡死堆栈信息或者bugly也没有捕获到异常,你是否很焦急?本文介绍一下我们项目中检测Unity卡死的方法,也许适合你使用. 实现原理 在绝大 ...

  5. Git-commit-中添加表情

    git commit 中使用表情 我们经常可以在github上看到国外大佬的commit信息中有很多可爱的表情,这是怎么做到的呢? ok,可以这样使用哦:git commit -m '提交信息 :em ...

  6. Java二进制和位运算,这一万字准能喂饱你

    基础不牢,地动山摇.本文已被 https://www.yourbatman.cn 收录,里面一并有Spring技术栈.MyBatis.JVM.中间件等小而美的专栏供以免费学习.关注公众号[BAT的乌托 ...

  7. C语言基础练习——打印菱形

    C语言基础练习--打印菱形 JERRY_Z. ~ 2020 / 8 / 26 转载请注明出处! 代码: /* * @Author: JERRY_Z. * @Date: 2020-08-26 17:17 ...

  8. TypeError 之 Cannot convert undefined or null to object

    分享一个今天遇到的一个bug , 希望对你也有用. 1.Object.keys()中传错了参数 2.由于undefined和null无法转成对象,所以如果它们做为Object.assign()的参数( ...

  9. rpc中的注册中心

    使用模板模式,对注册中心进行设计,可以方便后续添加注册中心 模板抽象类,提供注册中心必要的方法. public abstract class ServiceRegistry { //这是一个模板的抽象 ...

  10. mock之初体验

    刚接触vue的时候,看到github上有人的开源项目介绍使用mock可以模拟接口调用,可以使用模拟数据避免跟后端交互也可以实现前端功能的完美展现,当时觉得卧槽,mock这个东西这么神奇的吗?那一定要学 ...