极坐标系减去顺序并不重要(显然)

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

我想使用

polars
,但是当我尝试从 DataFrame 的三列中减去 1x3 numpy 数组时。问题是减法的应用顺序并不重要:

import numpy as np
import polars as pl

# create polars dataframe:
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df = pl.DataFrame(data, schema=['x', 'y', 'z']).with_columns(
    pl.all().cast(pl.Float64)
)

# subraction array:
arr = np.array([2, 5, 8], dtype=np.float64)

# subtract shit array from DataFrame
df.with_columns((
    pl.col('x') - arr[0],
    pl.col('y') - arr[1],
    pl.col('z') - arr[2],
))


"""
This one is corrct, top row should be negative and bottom row positive
|    |   x |   y |   z |
|---:|----:|----:|----:|
|  0 |  -1 |  -1 |  -1 |
|  1 |   0 |   0 |   0 |
|  2 |   1 |   1 |   1 |
"""

df.with_columns((
    arr[0] - pl.col('x'),
    arr[1] - pl.col('y'),
    arr[2] - pl.col('z'),
))

"""
This one is incorrect. The top row should be positive and the bottom row should
be negative.
|    |   x |   y |   z |
|---:|----:|----:|----:|
|  0 |  -1 |  -1 |  -1 |
|  1 |   0 |   0 |   0 |
|  2 |   1 |   1 |   1 |
"""
python numpy operation python-polars
1个回答
3
投票

无法重现这个,从我看来很好

0.16.5

In [57]: df.with_columns((
    ...:     pl.col('x') - arr[0],
    ...:     pl.col('y') - arr[1],
    ...:     pl.col('z') - arr[2],
    ...: ))
    ...:
Out[57]:
shape: (3, 3)
┌──────┬──────┬──────┐
│ x    ┆ y    ┆ z    │
│ ---  ┆ ---  ┆ ---  │
│ f64  ┆ f64  ┆ f64  │
╞══════╪══════╪══════╡
│ -1.0 ┆ -1.0 ┆ -1.0 │
│ 0.0  ┆ 0.0  ┆ 0.0  │
│ 1.0  ┆ 1.0  ┆ 1.0  │
└──────┴──────┴──────┘

In [58]: df.with_columns((
    ...:     arr[0] - pl.col('x'),
    ...:     arr[1] - pl.col('y'),
    ...:     arr[2] - pl.col('z'),
    ...: ))
Out[58]:
shape: (3, 3)
┌──────┬──────┬──────┐
│ x    ┆ y    ┆ z    │
│ ---  ┆ ---  ┆ ---  │
│ f64  ┆ f64  ┆ f64  │
╞══════╪══════╪══════╡
│ 1.0  ┆ 1.0  ┆ 1.0  │
│ 0.0  ┆ 0.0  ┆ 0.0  │
│ -1.0 ┆ -1.0 ┆ -1.0 │
└──────┴──────┴──────┘
© www.soinside.com 2019 - 2024. All rights reserved.