Python 为什么比香草df.apply更快更慢?
我有一个100万行的数据帧。我有一个单独的函数(我不能矢量化)应用于每一行。我研究了swifter,它承诺利用多个进程来加速计算。但在8核机器上,情况并非如此 知道为什么吗Python 为什么比香草df.apply更快更慢?,python,pandas,swifter,Python,Pandas,Swifter,我有一个100万行的数据帧。我有一个单独的函数(我不能矢量化)应用于每一行。我研究了swifter,它承诺利用多个进程来加速计算。但在8核机器上,情况并非如此 知道为什么吗 def parse_row(n_print=None): def f(row): if n_print is not None and row.name % n_print == 0: print(row.name, end="\r") return Featu
def parse_row(n_print=None):
def f(row):
if n_print is not None and row.name % n_print == 0:
print(row.name, end="\r")
return Feature(
geometry=Point((float(row["longitude"]), float(row["latitude"]))),
properties={
"water_level": float(row["water_level"]),
"return_period": float(row["return_period"])
}
)
return f
In [12]: df["feature"] = df.swifter.apply(parse_row(), axis=1)
Dask Apply: 100%|████████████████████████████████████████| 48/48 [01:19<00:00, 1.65s/it]
In [13]: t = time(); df["feature"] = df.apply(parse_row(), axis=1); print(int(time() - t))
46
def parse_行(n_print=None):
def f(世界其他地区):
如果n_print不是None且row.name%n_print==0:
打印(row.name,end=“\r”)
返回特性(
几何图形=点((浮动(行[“经度])、浮动(行[“纬度])),
性质={
“水位”:浮子(第[“水位”行]),
“返回周期”:浮动(第[“返回周期”]行)
}
)
返回f
[12]中:df[“feature”]=df.swifter.apply(parse_row(),axis=1)
Dask应用:100%|████████████████████████████████████████| 48/48[01:19这主要取决于所涉及的处理能力,以及矢量化/并行处理/优化是否可以改善问题。有时这根本不是一个解决方案。
还要记住,swifter需要时间来计算其预计的工作时间跨度,有时df.apply会更快,因为它不必计算,优化也可能没有帮助。看起来速度取决于行的大小。此df.swifter.apply(λx:1,如果x>5,则为0)当尺寸(df)时,比简单应用慢