小编leb*_*gue的帖子

如何在极坐标选择或分组上下文中进行回归(例如简单线性)?

我用极地代替熊猫。我对速度和惰性计算/评估感到非常惊讶。目前,有很多关于惰性数据帧的方法,但它们只能驱使我到目前为止。

因此,我想知道将极坐标与其他工具结合使用以实现更复杂的操作(例如回归/模型拟合)的最佳方法是什么。

更具体地说,我将举一个涉及线性回归的例子。

假设我有一个包含 day、y、x1 和 x2 列的极坐标数据框,并且我想生成一个序列,它是按天对 x1 和 x2 进行回归 y 的残差。我包含了如下代码示例以及如何使用 pandas 和 statsmodels 解决它。如何使用惯用的极坐标以最有效的方式获得相同的结果?

import pandas as pd
import statsmodels.api as sm

def regress_resid(df, yvar, xvars):
    result = sm.OLS(df[yvar], sm.add_constant(df[xvars])).fit()
    return result.resid

df = pd.DataFrame(
    {
        "day": [1, 1, 1, 1, 1, 2, 2, 2, 2, 2],
        "y": [1, 6, 3, 2, 8, 4, 5, 2, 7, 3],
        "x1": [1, 8, 2, 3, 5, 2, 1, 2, 7, 3],
        "x2": [8, 5, 3, 6, 3, 7, …
Run Code Online (Sandbox Code Playgroud)

python python-polars

8
推荐指数
1
解决办法
2074
查看次数

使用 Polars 实现 qcut 功能

我一直在使用 Polars,但它似乎缺乏 pandas 那样的 qcut 功能。

我不确定原因,但是使用当前可用的 Polars 功能是否可以达到与 pandas qcut 相同的效果?

下面显示了一个关于我可以使用 pandas qcut 做什么的示例。

import pandas as pd

data = pd.Series([11, 1, 2, 2, 3, 4, 5, 1, 2, 3, 4, 5])
pd.qcut(data, [0, 0.2, 0.4, 0.6, 0.8, 1], labels=['q1', 'q2', 'q3', 'q4', 'q5'])
Run Code Online (Sandbox Code Playgroud)

结果如下:

0     q5
1     q1
2     q1
3     q1
4     q3
5     q4
6     q5
7     q1
8     q1
9     q3
10    q4
11    q5
dtype: category
Run Code Online (Sandbox Code Playgroud)

所以,我很好奇如何使用极坐标得到相同的结果?

感谢您的帮助。

python python-polars

6
推荐指数
1
解决办法
874
查看次数

如何在 Polars 中更有效地执行条件连接?

我手头有一个相当大的数据框。将其自身加入需要一些时间。但我想将它们加入一些条件,这可能会使生成的数据帧小得多。我的问题是如何利用这些条件使条件连接比普通完全连接更快?

下面的代码用于说明:

import time
import numpy as np
import polars as pl

# example dataframe
rng = np.random.default_rng(1)

nrows = 3_000_000
df = pl.DataFrame(
    dict(
        day=rng.integers(1, 300, nrows),
        id=rng.integers(1, 5_000, nrows),
        id2=rng.integers(1, 5, nrows),
        value=rng.normal(0, 1, nrows),
    )
)

# joining df with itself takes around 10-15 seconds on a machine with 32 cores.
start = time.perf_counter()
df.join(df, on=["id", "id2"], how="left")
time.perf_counter() - start

# joining df with itself with extra conditions - the implementation below that takes very similar …
Run Code Online (Sandbox Code Playgroud)

python python-polars

3
推荐指数
1
解决办法
1865
查看次数

标签 统计

python ×3

python-polars ×3