python - 我可以将矢量化函数应用于 pandas 数据框吗?

标签 python pandas numpy dataframe vectorization

我对 pandasnumpy 还很陌生,我正在尝试找出做某些事情的最佳方法。

现在我正在尝试在数据帧的每一行上调用一个函数。如果我向此函数传递三个 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

最佳答案

目前尚不清楚您为何尝试使用apply。您只需执行 beta.cdf(df.a, df.b, df.c) 即可。

关于python - 我可以将矢量化函数应用于 pandas 数据框吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40196231/

相关文章:

javascript - 无法将多个查询的数据发送到django中的ajax调用

python - 将具有不同名称的多列上的数据帧从宽格式转换为长格式

python - 使用 python 中数组的索引切片二维数组

python - 具有两个条件的 if 语句

python - Pandas 浮点小数

python - 如何在 Python 中实现平均感知器(不使用 Scikit-learn)

python - 读取交错数据的快速方法?

python - 类型错误 : 'str' object is not callable when insert tweet data to mysql Python 3

python - 如何将 Airflow dag 配置为每天在特定时间运行?

python - 将函数应用于 Spark DataFrame 中的所有单元格