我是pandas
和numpy
的新手,我试图找出做某些事情的最佳方法。我可以将矢量化函数应用于熊猫数据框吗?
现在我正试图调用dataframe
的每一行上的函数。如果我将三个numpy
阵列传递给此函数,它非常快,但在dataframe
上使用apply
的速度非常慢。
我的猜测是numpy
在第一种情况下使用矢量化函数,而不是在第二种情况下。有没有办法让pandas
使用该优化?基本上,在伪代码,我认为apply
正在做类似for row in frame: func(row['a'], row['b'], row['c'])
,但我希望它做func(col['a'], col['b'], col['c'])
。
这是我正在尝试做的一个例子。
import numpy as np
import pandas as pd
from scipy.stats import beta
count = 100000
# If I start with a given dataframe and use apply, it's very slow
df = pd.DataFrame(np.random.uniform(0, 1, size=(count, 3)), columns=['a', 'b', 'c'])
df.apply(lambda frame: beta.cdf(frame['a'], frame['b'], frame['c']), axis=1)
# However, if I split out each column into a numpy array, this is very fast.
a = df['a'].as_matrix()
b = df['b'].as_matrix()
c = df['c'].as_matrix()
beta.cdf(a, b, c)
# But at this point I've lost the context of the dataframe.
# I would like to keep the results in a new column for further processing
向量化将是函数特定的。那么,你是否试图向矢量化那个'beta.cdf'或者可能有其他的? – Divakar
所以beta.cdf已经接受数组(和系列)为什么你使用apply而不是那个? – ayhan
为什么不直接调用'beta.cdf(df.a,df.b,df.c)'? – BrenBarn