【发布时间】:2017-04-06 23:12:19
【问题描述】:
pandas df.apply(x, axis=1) 方法是同时还是迭代地将函数 x 应用于所有行?我查看了文档,但没有找到任何东西。
【问题讨论】:
-
矢量化函数实际上并不同时应用于所有行。无论如何,有关一些详细信息,请参阅答案here。
pandas df.apply(x, axis=1) 方法是同时还是迭代地将函数 x 应用于所有行?我查看了文档,但没有找到任何东西。
【问题讨论】:
它是迭代的:
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"])
In [12]: def f(row):
f.count += 1
return f.count
In [13]: f.count = 0
In [14]: df.apply(f, axis=1)
Out[14]:
0 1
1 2
dtype: int64
注意:尽管在此示例中似乎并非如此 the documentation 警告:
在当前实现中,apply 在第一列/行上调用 func 两次,以决定它是否可以采用快速或慢速代码路径。如果 func 有副作用,这可能会导致意外行为,因为它们会对第一列/行生效两次。
实际的 for 循环(用于 python 函数而不是 ufunc)发生在 lib.reduce (here) 中。
【讨论】:
我相信迭代是答案。考虑一下:
import pandas as pd
import numpy as np
import time
# Make a 1000 row long dataframe
df = pd.DataFrame(np.random.random((1000, 4)))
# Apply this time delta function over the length of the dataframe
t0 = time.time()
times = df.apply(lambda _: time.time()-t0, axis=1)
# Print some of the results
print(times[::100])
输出[]:
0 0.000500
100 0.001029
200 0.001532
300 0.002036
400 0.002531
500 0.003033
600 0.003536
700 0.004035
800 0.004537
900 0.005513
数据类型:float64
【讨论】: