我想将极坐标数据帧行除以单行数据帧。 在 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/