代码之家  ›  专栏  ›  技术社区  ›  jss367

Python polars:在pl.DataFrame列中为每个唯一值创建行,为另一列创建列,为第三列创建值

  •  1
  • jss367  · 技术社区  · 1 年前

    我有一个Polars DataFrame,它看起来像这样:

    d = {'id': ['N/A', 'N/A', '1', '1', '2'], 'type': ['red', 'blue', 'yellow', 'green', 'yellow'], 'area': [0, 0, 3, 4, 5]}
    dp = pl.DataFrame(d)
    shape: (5, 3)
    ┌─────┬────────┬──────┐
    │ id  ┆ type   ┆ area │
    │ --- ┆ ---    ┆ ---  │
    │ str ┆ str    ┆ i64  │
    ╞═════╪════════╪══════╡
    │ N/A ┆ red    ┆ 0    │
    │ N/A ┆ blue   ┆ 0    │
    │ 1   ┆ yellow ┆ 3    │
    │ 1   ┆ green  ┆ 4    │
    │ 2   ┆ yellow ┆ 5    │
    └─────┴────────┴──────┘
    

    我想做一些透视或转置操作,这样每一行都是一个id(不包括“N/A”),每种类型都有一列,值就是面积。如果没有给出任何值,它应该为零。因此,在这种情况下,结果应该是这样的:

          red   blue  yellow  green
    '1'    0      0     3      4
    '2'    0      0     5      0
    

    我怎么能在波兰做到这一点?我宁愿避免把整件事变成熊猫。

    2 回复  |  直到 1 年前
        1
  •  2
  •   Sajjad Ranjbar    1 年前

    在Polars中,可以通过使用枢轴操作来获得所需的结果。以下是针对特定DataFrame的操作方法:

    import polars as pl
    
    d = {
        'id': ['N/A', 'N/A', '1', '1', '2'],
        'type': ['red', 'blue', 'yellow', 'green', 'yellow'],
        'area': [0, 0, 3, 4, 5]
    }
    
    dp = pl.DataFrame(d)
    
    # Remove rows with 'N/A' in the 'id' column
    dp = dp.filter(pl.col("id") != "N/A")
    
    # Perform the pivot operation
    dp = dp.pivot('id', 'type', 'area', aggfn='first')
    
    # Fill missing values with 0
    dp = dp.fill_null(0)
    
    print(dp)
    

    输出:

    shape: (2, 4)
    ┌─────┬──────┬───────┬──────┐
    │ id  ┆ blue ┆ green ┆ red  │
    │ --- ┆ ---  ┆ ---   ┆ ---  │
    │ str ┆ i64  ┆ i64   ┆ i64  │
    ╞═════╪══════╪═══════╪══════╡
    │ 1   ┆ 0    ┆ 4     ┆ 0    │
    │ 2   ┆ 0    ┆ 0     ┆ 0    │
    └─────┴──────┴───────┴──────┘
    
        2
  •  1
  •   jqurious FObersteiner    1 年前
    (df.pivot('area', 'id', 'type', None)
       .filter(pl.col('id') != 'N/A')
    )
    
    shape: (2, 5)
    ┌─────┬──────┬──────┬────────┬───────┐
    │ id  ┆ red  ┆ blue ┆ yellow ┆ green │
    │ --- ┆ ---  ┆ ---  ┆ ---    ┆ ---   │
    │ str ┆ i64  ┆ i64  ┆ i64    ┆ i64   │
    ╞═════╪══════╪══════╪════════╪═══════╡
    │ 1   ┆ null ┆ null ┆ 3      ┆ 4     │
    │ 2   ┆ null ┆ null ┆ 5      ┆ null  │
    └─────┴──────┴──────┴────────┴───────┘