我正在try 将我的一些pandas代码切换为polars以利用其性能.我发现.滤镜操作比使用. loco的类似切片慢得多.

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

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

推荐答案

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

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

那么out[0]包含索引列匹配test_dates[0]的行,等等.

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

Pandas 0.029560166876763105
Polars 0.0009763331618160009

Python相关问答推荐

具有nan值的列之间的比率.如何为每一行 Select pandas中没有nan值的列?

等待元素出现在Selenium中(WebDriverWait)

为什么使用SciPy中的Distance. cos函数比直接执行其Python代码更快?

为什么我的主页不会重定向到详细视图(Django)

将词典写入Excel

telegram 机器人API setMyName不起作用

使用from_pandas将GeDataFrame转换为polars失败,ArrowType错误:未传递numpy. dype对象

如何用symy更新分段函数

添加包含中具有任何值的其他列的计数的列

LAB中的增强数组

如何在箱形图中添加绘制线的传奇?

当使用keras.utils.Image_dataset_from_directory仅加载测试数据集时,结果不同

处理带有间隙(空)的duckDB上的重复副本并有效填充它们

Python库:可选地支持numpy类型,而不依赖于numpy

如何使用根据其他值相似的列从列表中获取的中间值填充空NaN数据

如何在python polars中停止otherate(),当使用when()表达式时?

如何在UserSerializer中添加显式字段?

如何并行化/加速并行numba代码?

使用BeautifulSoup抓取所有链接

Python—转换日期:价目表到新行