欢迎来我的个人Blog获得更好的阅读体验。
太长懒得看版
使用
map
函数进行行计算,加上np.column_stack
进行合并最快
假如有这么一组数据
df = pd.DataFrame({"one":list("AABBCCDD"),
"two":[1,1,2,2,3,3,4,4],
"three":[9,9,8,8,7,7,6,6]})
现在我假如要对two和three进行这么一个函数计算
def cal_func(a,b):
return math.sqrt(a**2+b**2)
然后生成一列新的叫作four这么一列。
于是乎现在有两种方法:
- 使用pandas的apply;
- 转为二维数组,使用map进行计算。
那么到底那种更快呢?
实践是检验真理的唯一标准
1.使用apply方法
%%time
df["four"] = df.apply(lambda x:cal_func(x.two, x.three), axis=1)
print(df)
one two three new
0 A 1 9 9.055385
1 A 1 9 9.055385
2 B 2 8 8.246211
3 B 2 8 8.246211
4 C 3 7 7.615773
5 C 3 7 7.615773
6 D 4 6 7.211103
7 D 4 6 7.211103
CPU times: user 13.1 ms, sys: 0 ns, total: 13.1 ms
Wall time: 13.1 ms
我们看到,花了13.1ms
2.使用map方法
首先转成np.array,df_array = df.values
然后使用map方法
这里为了测试合并矩阵,还选用了不同的合并方法进行对比,分别为:
- np.insert
- np.column_stack
- np.c_
- 直接用list的append
2.1 np.insert
%%time
np.insert(df_array, -1, values=list(map(lambda x:cal_func(x[1], x[2]), df_array)), axis=1)
CPU times: user 235 µs, sys: 0 ns, total: 235 µs
Wall time: 247 µs
array([['A', 1, 9.055385138137417, 9],
['A', 1, 9.055385138137417, 9],
['B', 2, 8.246211251235321, 8],
['B', 2, 8.246211251235321, 8],
['C', 3, 7.615773105863909, 7],
['C', 3, 7.615773105863909, 7],
['D', 4, 7.211102550927978, 6],
['D', 4, 7.211102550927978, 6]], dtype=object)
2.2 np.column_stack
%%time
np.column_stack((df_array, list(map(lambda x:cal_func(x[1], x[2]), df_array))))
CPU times: user 145 µs, sys: 0 ns, total: 145 µs
Wall time: 157 µs
array([['A', 1, 9, 9.055385138137417],
['A', 1, 9, 9.055385138137417],
['B', 2, 8, 8.246211251235321],
['B', 2, 8, 8.246211251235321],
['C', 3, 7, 7.615773105863909],
['C', 3, 7, 7.615773105863909],
['D', 4, 6, 7.211102550927978],
['D', 4, 6, 7.211102550927978]], dtype=object)
2.3 np.c_
%%time
np.c_[df_array, list(map(lambda x:cal_func(x[1], x[2]), df_array))]
CPU times: user 279 µs, sys: 0 ns, total: 279 µs
Wall time: 290 µs
array([['A', 1, 9, 9.055385138137417],
['A', 1, 9, 9.055385138137417],
['B', 2, 8, 8.246211251235321],
['B', 2, 8, 8.246211251235321],
['C', 3, 7, 7.615773105863909],
['C', 3, 7, 7.615773105863909],
['D', 4, 6, 7.211102550927978],
['D', 4, 6, 7.211102550927978]], dtype=object)
2.4 list append
df_list = df_array.tolist()
for idx, value in enumerate(map(lambda x:cal_func(x[1], x[2]), df_list)):
df_list[idx].append(value)
print(df_list)
[['A', 1, 9, 9.055385138137417], ['A', 1, 9, 9.055385138137417], ['B', 2, 8, 8.246211251235321], ['B', 2, 8, 8.246211251235321], ['C', 3, 7, 7.615773105863909], ['C', 3, 7, 7.615773105863909], ['D', 4, 6, 7.211102550927978], ['D', 4, 6, 7.211102550927978]]
CPU times: user 220 µs, sys: 0 ns, total: 220 µs
Wall time: 233 µs
对比
方法 | 时间 |
---|---|
df.apply | 13.1ms |
np.insert, map | 247 µs |
np.column_stack, map | 157 µs |
np.c_, map | 290 µs |
list.append, map | 233 µs |
最后得出, np.column_stack + map的方法最快