11种方法对比Pandas双列求和
本文介绍的是通过11种方法来对比Pandas中DataFrame两列的求和
- direct_add
- for_iloc
- iloc_sum
- iat
- apply(指定字段)
- apply(针对整个DataFrame)
- numpy_array
- iterrows
- zip
- assign
- sum
数据模拟
为了效果明显,模拟了一份5万条的数据,4个字段:
1 | import pandas as pd |
11种函数
下面是通过11种不同的函数来实现A、C两列的数据相加求和E列
方法1:直接相加
把df的两列直接相加
In [3]:
1 | def fun1(df): |
方法2:for+iloc定位
for语句 + iloc方法的遍历循环
In [4]:
1 | def fun2(df): |
方法3:iloc + sum
iloc方法针对全部行指定列的求和:
- 0:第一列A
- 2:第三列C
In [5]:
1 | def fun3(df): |
方法3:iat定位
for语句 + iat定位,类比于for + iloc
In [6]:
1 | def fun4(df): |
apply函数(只读两列)
apply方法 ,仅仅取出AC两列
In [7]:
1 | def fun5(df): |
apply函数(全部df)
针对前部的DataFrame使用apply方法
In [8]:
1 | def fun6(df): |
numpy数组
使用numpy数组解决
In [9]:
1 | def fun7(df): |
iterrows迭代
iterrows()迭代每行的数据
In [10]:
1 | def fun8(df): |
zip函数
通过zip函数现将AC两列的数据进行压缩
In [11]:
1 | def fun9(df): |
assign函数
通过派生函数assign生成新的字段E
In [12]:
1 | def fun10(df): |
sum函数
在指定的A、C两列上使用sum函数
In [13]:
1 | def fun11(df): |
结果
调用11种函数,比较它们的速度:
统计每种方法下的均值,并整理成相同的us:
方法 | 结果 | 统一(us) |
---|---|---|
直接相加 | 626us | 626 |
for + iloc | 9.61s | 9610000 |
iloc + sum | 1.42ms | 1420 |
iat | 9.2s | 9200000 |
apply(只取指定列) | 666ms | 666000 |
apply(全部列) | 697ms | 697000 |
numpy | 216us | 216 |
iterrows | 3.29s | 3290000 |
zip | 17.9ms | 17900 |
assign | 888us | 888 |
sum(axis=1) | 1.33ms | 1330 |
1 | result = pd.DataFrame({"methods":["direct_add","for_iloc","iloc_sum","iat","apply_part","apply_all", |
进行降序后的可视化:
1 | result.sort_values("time",ascending=False,inplace=True) |
从结果中能够看到:
- for循环是最耗时的,使用numpy数组最省时间,相差4万多倍;主要是因为Numpy数组使用的向量化操作
- sum函数(指定轴axis=1)对效果的提升很明显
总结:循环能省则省,尽可能用Pandas或者numpy的内置函数来解决。