这是我第一次使用Polar数据框.我正在try 将输入值与Postgres表中的数据进行匹配. 分享一些示例代码,这是实际代码的一部分. 我有一个名为"Score"的列,类型为list[i32].作为下一步,我试图找到该列表中的最大值.我得到错误.

import polars as pl
import jaro


def test_polars():
    fname='sarah'
    lname = 'vatssss'
    data = {"first_name": ['sarah', 'purnima'], "last_name": ['vats', 'malik']}
    df = pl.DataFrame(data)
    print(df)
    df = (df.with_columns(
        [
            (pl.when(pl.col("first_name") == fname).then(1).otherwise(0)).alias("E_FN"),
            (pl.when(pl.col("last_name") == lname).then(1).otherwise(0)).alias("E_LN"),
            (pl.when(pl.col("first_name").str.slice(0, 3) == fname[0:3]).then(1).otherwise(0)).alias("F3_FN"),
            (pl.when(pl.col("first_name").map_elements(
                lambda first_name: jaro.jaro_winkler_metric(first_name, fname)) >= 0.8).then(1).otherwise(0)).alias(
                "CMP80_FN"),
            (pl.when(pl.col("last_name").map_elements(
                lambda first_name: jaro.jaro_winkler_metric(first_name, lname)) >= 0.9).then(1).otherwise(0)).alias(
                "CMP90_LN"),

        ]
    )
    .with_columns(
        [ pl.concat_list(980 * pl.col("E_FN")  ,
                         970 * pl.col("E_LN") ).alias("score")



        ]
    )
    .with_columns(
        [pl.max(pl.col("score")).alias("max_score")

         ]
    )

    )

    print(df)


if __name__ == '__main__':
    test_polars()

C:\PythonProject\pythonProject\venv\Graph_POC\Scripts\python.exe "C:\PythonProject\pythonProject\polars data.py" 
shape: (2, 2)
┌────────────┬───────────┐
│ first_name ┆ last_name │
│ ---        ┆ ---       │
│ str        ┆ str       │
╞════════════╪═══════════╡
│ sarah      ┆ vats      │
│ purnima    ┆ malik     │
└────────────┴───────────┘
Traceback (most recent call last):
  File "C:\PythonProject\pythonProject\polars data.py", line 45, in <module>
    test_polars()
  File "C:\PythonProject\pythonProject\polars data.py", line 34, in test_polars
    [pl.max(pl.col("score")).alias("max_score")
     ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\PythonProject\pythonProject\venv\Graph_POC\Lib\site-packages\polars\functions\aggregation\vertical.py", line 175, in max
    return F.col(*names).max()
           ^^^^^^^^^^^^^
  File "C:\PythonProject\pythonProject\venv\Graph_POC\Lib\site-packages\polars\functions\col.py", line 288, in __new__
    return _create_col(name, *more_names)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\PythonProject\pythonProject\venv\Graph_POC\Lib\site-packages\polars\functions\col.py", line 67, in _create_col
    raise TypeError(msg)
TypeError: invalid input for `col`

Expected `str` or `DataType`, got 'Expr'.

Process finished with exit code 1

推荐答案

您可以使用list.max()函数.简单的例子:

df = pl.DataFrame(
    {
        "a": [[1, 8, 3],[6,2,7],[8,10,11]],
        "b": [4, 5, None],
    }
)

┌─────────────┬──────┐
│ a           ┆ b    │
│ ---         ┆ ---  │
│ list[i64]   ┆ i64  │
╞═════════════╪══════╡
│ [1, 8, 3]   ┆ 4    │
│ [6, 2, 7]   ┆ 5    │
│ [8, 10, 11] ┆ null │
└─────────────┴──────┘

df.with_columns(
    pl.col('a').list.max().alias('max_a')
)

┌─────────────┬──────┬───────┐
│ a           ┆ b    ┆ max_a │
│ ---         ┆ ---  ┆ ---   │
│ list[i64]   ┆ i64  ┆ i64   │
╞═════════════╪══════╪═══════╡
│ [1, 8, 3]   ┆ 4    ┆ 8     │
│ [6, 2, 7]   ┆ 5    ┆ 7     │
│ [8, 10, 11] ┆ null ┆ 11    │
└─────────────┴──────┴───────┘

所以在你的情况下,只使用pl.col("score").list.max而不是pl.max(pl.col("score")).max()只是col(names).max()的语法糖,应该返回列的最大值,而不是列的列表类型单元格的最大值.

Python相关问答推荐

如何根据日期和时间将状态更新为已过期或活动?

Pythind 11无法弄清楚如何访问tuple元素

如何使用scipy从频谱图中回归多个高斯峰?

更改matplotlib彩色条的字体并勾选标签?

DataFrame groupby函数从列返回数组而不是值

如何将ctyles.POINTER(ctyles.c_float)转换为int?

如何让剧作家等待Python中出现特定cookie(然后返回它)?

有症状地 destruct 了Python中的regex?

基于字符串匹配条件合并两个帧

基于索引值的Pandas DataFrame条件填充

如何使Matplotlib标题以图形为中心,而图例框则以图形为中心

如何并行化/加速并行numba代码?

如何在Python中获取`Genericums`超级类型?

让函数调用方程

交替字符串位置的正则表达式

如何将数据帧中的timedelta转换为datetime

如何在Great Table中处理inf和nans

每次查询的流通股数量

删除另一个div中的特定div容器

pyspark where子句可以在不存在的列上工作