你可以通过传递整个向量来向量化DataFrame
to np.trapz http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.trapz.html并指定axis=
论证,例如:
import numpy as np
import pandas as pd
# some random input data
gen = np.random.RandomState(0)
x = gen.randn(100, 10)
names = [chr(97 + i) for i in range(10)]
forces = pd.DataFrame(x, columns=names)
# vectorized version
wrk = np.trapz(forces, x=forces.index, axis=0)
work_done = pd.DataFrame(wrk[None, :], columns=forces.columns)
# non-vectorized version for comparison
work_done2 = {}
for col in forces.columns:
work_done2.update({col:np.trapz(forces.loc[:, col], forces.index)})
这些给出以下输出:
from pprint import pprint
pprint(work_done.T)
# 0
# a -24.331560
# b -10.347663
# c 4.662212
# d -12.536040
# e -10.276861
# f 3.406740
# g -3.712674
# h -9.508454
# i -1.044931
# j 15.165782
pprint(work_done2)
# {'a': -24.331559643023006,
# 'b': -10.347663159421426,
# 'c': 4.6622123535050459,
# 'd': -12.536039649161403,
# 'e': -10.276861220217308,
# 'f': 3.4067399176289994,
# 'g': -3.7126739591045541,
# 'h': -9.5084536839888187,
# 'i': -1.0449311137294459,
# 'j': 15.165781517623724}
您的原始示例还存在一些其他问题。col
是列名而不是行索引,因此它需要索引数据帧的第二个维度(即.loc[:, col]
而不是.loc[col]
)。另外,最后一行有一个额外的尾括号。
Edit:
You could还生成输出DataFrame
直接由.apply http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.apply.htmling np.trapz
到每一列,例如:
work_done = forces.apply(np.trapz, axis=0, args=(forces.index,))
然而,这并不是真正的“正确”矢量化 - 您仍在调用np.trapz
分别在每一列上。您可以通过比较速度来看到这一点.apply
反对打电话的版本np.trapz
直接地:
In [1]: %timeit forces.apply(np.trapz, axis=0, args=(forces.index,))
1000 loops, best of 3: 582 µs per loop
In [2]: %timeit np.trapz(forces, x=forces.index, axis=0)
The slowest run took 6.04 times longer than the fastest. This could mean that an
intermediate result is being cached
10000 loops, best of 3: 53.4 µs per loop
这不是一个完全公平的比较,因为第二个版本排除了构建DataFrame
来自输出 numpy 数组,但这应该仍然小于执行实际积分所需的时间差。