Polars Python 中按列的条件求和

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

我不知道如何在列中执行条件求和,但我想知道如何实现类似的方法并最终作为数据框

import pandas as pd

df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'C'],
                'conference': ['East', 'East', 'East', 'West', 'West', 'East'],
                'points': [11, 8, 10, 6, 6, 5],
                'rebounds': [7, 7, 6, 9, 12, 8]})

pl.from_pandas(df)
┌──────┬────────────┬────────┬──────────┐
│ team ┆ conference ┆ points ┆ rebounds │
│ ---  ┆ ---        ┆ ---    ┆ ---      │
│ str  ┆ str        ┆ i64    ┆ i64      │
╞══════╪════════════╪════════╪══════════╡
│ A    ┆ East       ┆ 11     ┆ 7        │
│ A    ┆ East       ┆ 8      ┆ 7        │
│ A    ┆ East       ┆ 10     ┆ 6        │
│ B    ┆ West       ┆ 6      ┆ 9        │
│ B    ┆ West       ┆ 6      ┆ 12       │
│ C    ┆ East       ┆ 5      ┆ 8        │
└──────┴────────────┴────────┴──────────┘

熊猫解决方案:

df.loc[(df2['points'] >= 8) & (df['team'] != 8), 'rebounds'].sum()
df.query("points >= 8 and team != 'B' ")['rebounds'].sum()

结果:

20
┌─────────┬──────────┐
│ column  ┆ column_0 │
│ ---     ┆ ---      │
│ str     ┆ u32      │
╞═════════╪══════════╡
│ group_a ┆ 20       │
│ group_b ┆ 10       │
└─────────┴──────────┘
python python-polars
1个回答
2
投票
df.select([
    pl.col("rebounds").where((pl.col("points") >= 8) & (pl.col("team") != 'B')).sum()
])
shape: (1, 1)
┌──────────┐
│ rebounds │
│ ---      │
│ i64      │
╞══════════╡
│ 20       │
└──────────┘
© www.soinside.com 2019 - 2024. All rights reserved.