使用 Polars .filter 进行切片比 pandas .loc 慢

问题描述 投票:0回答:1

我正在尝试将我的一些 Pandas 代码切换为 Polars 以利用它的性能。我发现 .filter 操作比使用 .loc 的类似切片慢得多。

import pandas as pd
import polars as pl
import datetime as dt
import numpy as np

date_index = pd.date_range(dt.date(2001,1,1), dt.date(2020,1,1),freq='1H')
n = date_index.shape[0]
test_pd = pd.DataFrame(data = np.random.randint(1,100, n), index=date_index, columns = ['test'])
test_pl = pl.DataFrame(test_pd.reset_index())
test_dates = date_index[np.random.randint(0,n,1000)]

st = time.perf_counter()
for i in test_dates:
    d = test_pd.loc[i,:]
print(f"Pandas {time.perf_counter() - st}")


st = time.perf_counter()
for i in test_dates:
    d = test_pl.filter(index=i)
print(f"Polars {time.perf_counter() - st}")

Pandas 0.1854726000019582
Polars 2.1125728000042727

还有其他方法可以加速极坐标中的切片操作吗?

python dataframe python-polars
1个回答
1
投票

Polars 不使用索引,因此随机访问一个特定元素(如果不是按行号)将始终必须循环遍历所有数据。但是您可以使用联接一次性有效地获取您感兴趣的所有日期:

test_dates_df = pl.DataFrame({"index": test_dates})
ds = test_dates_df.join(test_pl, on="index", how="left")

在我的机器上,给出以下时间:

Pandas 0.029560166876763105
Polars 0.0009763331618160009
© www.soinside.com 2019 - 2024. All rights reserved.