python - 用极坐标中的一个行框架划分数据帧行

标签 python pandas python-polars

我想将极坐标数据帧行除以单行数据帧。 在 pandas 中,可以使用 df.divide 来完成。 还没有找到如何在极地做到这一点。

我取得了这样的结果:

from itertools import repeat
import polars as pl
data = {'a': [i for i in range(1, 5)],
            'b': [i for i in range(1, 5)],
            'c': [i for i in range(1, 5)],
            'd': [i for i in range(1, 5)]}
    df = pl.DataFrame(data)
    divisors = pl.DataFrame({'d1': 1, 'd2': 10, 'd3': 100, 'd4': 1000})
    divisors_as_big_as_df = pl.concat([item for item in repeat(divisors, len(df))])
    divided_df = df / divisors_as_big_as_df
    print(df)
    print(divisors)
    print(divisors_as_big_as_df)
    print(divided_df)

这是输出:

shape: (4, 4)
┌─────┬─────┬─────┬─────┐
│ a   ┆ b   ┆ c   ┆ d   │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╪═════╡
│ 1   ┆ 1   ┆ 1   ┆ 1   │
│ 2   ┆ 2   ┆ 2   ┆ 2   │
│ 3   ┆ 3   ┆ 3   ┆ 3   │
│ 4   ┆ 4   ┆ 4   ┆ 4   │
└─────┴─────┴─────┴─────┘
shape: (1, 4)
┌─────┬─────┬─────┬──────┐
│ d1  ┆ d2  ┆ d3  ┆ d4   │
│ --- ┆ --- ┆ --- ┆ ---  │
│ i64 ┆ i64 ┆ i64 ┆ i64  │
╞═════╪═════╪═════╪══════╡
│ 1   ┆ 10  ┆ 100 ┆ 1000 │
└─────┴─────┴─────┴──────┘
shape: (4, 4)
┌─────┬─────┬─────┬──────┐
│ d1  ┆ d2  ┆ d3  ┆ d4   │
│ --- ┆ --- ┆ --- ┆ ---  │
│ i64 ┆ i64 ┆ i64 ┆ i64  │
╞═════╪═════╪═════╪══════╡
│ 1   ┆ 10  ┆ 100 ┆ 1000 │
│ 1   ┆ 10  ┆ 100 ┆ 1000 │
│ 1   ┆ 10  ┆ 100 ┆ 1000 │
│ 1   ┆ 10  ┆ 100 ┆ 1000 │
└─────┴─────┴─────┴──────┘
shape: (4, 4)
┌─────┬─────┬──────┬───────┐
│ a   ┆ b   ┆ c    ┆ d     │
│ --- ┆ --- ┆ ---  ┆ ---   │
│ f64 ┆ f64 ┆ f64  ┆ f64   │
╞═════╪═════╪══════╪═══════╡
│ 1.0 ┆ 0.1 ┆ 0.01 ┆ 0.001 │
│ 2.0 ┆ 0.2 ┆ 0.02 ┆ 0.002 │
│ 3.0 ┆ 0.3 ┆ 0.03 ┆ 0.003 │
│ 4.0 ┆ 0.4 ┆ 0.04 ┆ 0.004 │
└─────┴─────┴──────┴───────┘

但是制作 divisors_as_big_as_df 确实很耗时。 那么有没有更好的办法呢?

最佳答案

您可以只按列进行除法,而不是创建大量 df 来执行元素除法。

df.with_columns(
    **{col: pl.col(col) / divisors[f"d{i+1}"] for (i, col) in enumerate(df.columns)}
)
shape: (4, 4)
┌─────┬─────┬──────┬───────┐
│ a   ┆ b   ┆ c    ┆ d     │
│ --- ┆ --- ┆ ---  ┆ ---   │
│ f64 ┆ f64 ┆ f64  ┆ f64   │
╞═════╪═════╪══════╪═══════╡
│ 1.0 ┆ 0.1 ┆ 0.01 ┆ 0.001 │
│ 2.0 ┆ 0.2 ┆ 0.02 ┆ 0.002 │
│ 3.0 ┆ 0.3 ┆ 0.03 ┆ 0.003 │
│ 4.0 ┆ 0.4 ┆ 0.04 ┆ 0.004 │
└─────┴─────┴──────┴───────┘

关于python - 用极坐标中的一个行框架划分数据帧行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77548649/

相关文章:

python - xtol 在 minimize(method='Nelder-Mead') 中的作用是什么?

行的 python pandas 着色

python - 按组划分数据框

python - 我们如何在 polars 中对时间序列进行重新采样

python - pandas、polars 或 torch 中函数的高效迭代和应用?偷懒可能吗?

python - 为什么 sqlalchemy expunge 不起作用?

python - 如何在Tkinter界面中显示来自OpenCV的图像?

python - 画中画: "Cannot uninstall ' ipython'。这是一个 distutils 安装的项目,因此我们无法准确确定..."

python - 从列表列表中提取元素 - Python Pandas

python - Pandas - 格式化时间并删除尾随零