一列与所有其他数字的校正

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

开始于

import polars as pl
df = pl.DataFrame({
    'a': [1,2,3],
    'b': [4.,2.,6.],
    'c': ['w', 'a', 'r'],
    'd': [4, 1, 1]
})

如何获得

a
与所有其他数字列之间的相关性?

相当于 pandas:

In [30]: (
    ...:     pd.DataFrame({
    ...:         'a': [1,2,3],
    ...:         'b': [4.,2.,6.],
    ...:         'c': ['w', 'a', 'r'],
    ...:         'd': [4, 1, 1]
    ...:     })
    ...:     .corr()
    ...:     .loc['a']
    ...: )
Out[30]:
a    1.000000
b    0.500000
d   -0.866025
Name: a, dtype: float64

我已经尝试过了

(
    df.select(pl.col(pl.Int64).cast(pl.Float64), pl.col(pl.Float64))
    .select(pl.corr('a', pl.exclude('a')))
)

但是得到了

DuplicateError: the name 'a' is duplicate
python python-polars
2个回答
1
投票

有一个

DataFrame.corr()
,然后您可以过滤它。

df.select(
    pl.col(pl.Int64).cast(pl.Float64), 
    pl.col(pl.Float64)
).corr()
shape: (3, 3)
┌───────────┬───────────┬─────┐
│ a         ┆ d         ┆ b   │
│ ---       ┆ ---       ┆ --- │
│ f64       ┆ f64       ┆ f64 │
╞═══════════╪═══════════╪═════╡
│ 1.0       ┆ -0.866025 ┆ 0.5 │
│ -0.866025 ┆ 1.0       ┆ 0.0 │
│ 0.5       ┆ 0.0       ┆ 1.0 │
└───────────┴───────────┴─────┘

1
投票

这是我想出的一个解决方案:

numeric = df.select(pl.col(pl.Int64).cast(pl.Float64), pl.col(pl.Float64))

numeric.select(pl.corr('a', col).alias(f'corr_a_{col}') for col in numeric.columns if col != 'a')
shape: (1, 2)
┌───────────┬──────────┐
│ corr_a_d  ┆ corr_a_b │
│ ---       ┆ ---      │
│ f64       ┆ f64      │
╞═══════════╪══════════╡
│ -0.866025 ┆ 0.5      │
└───────────┴──────────┘

有没有一种方法可以做到这一点而不必分配给临时变量?

© www.soinside.com 2019 - 2024. All rights reserved.