有没有办法在极坐标中进行分组,同时保留其他列?

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

我目前正在尝试实现极坐标 group_by,同时保留

group_by
函数中的列以外的其他列。

这是我拥有的输入数据框的示例。

df = pl.from_repr("""
┌─────┬─────┬─────┬─────┐
│ SRC ┆ TGT ┆ IT  ┆ Cd  │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ f64 │
╞═════╪═════╪═════╪═════╡
│ 1   ┆ 1   ┆ 2   ┆ 3.0 │
│ 2   ┆ 1   ┆ 2   ┆ 4.0 │
│ 3   ┆ 1   ┆ 2   ┆ 3.0 │
│ 3   ┆ 2   ┆ 1   ┆ 8.0 │
└─────┴─────┴─────┴─────┘
""")

我想使用

['TGT', 'IT']
min('Cd')
进行分组,如下代码:

df.group_by('TGT', 'IT').agg(pl.col('Cd').min())

通过此代码行,我获得以下数据框。

┌─────┬─────┬─────┐
│ TGT ┆ IT  ┆ Cd  │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ f64 │
╞═════╪═════╪═════╡
│ 1   ┆ 2   ┆ 3.0 │
│ 2   ┆ 1   ┆ 8.0 │
└─────┴─────┴─────┘

这是我更想要的数据框

┌─────┬─────┬─────┬─────┐
│ SRC ┆ TGT ┆ IT  ┆ Cd  │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ f64 │
╞═════╪═════╪═════╪═════╡
│ 1   ┆ 1   ┆ 2   ┆ 3.0 │
│ 3   ┆ 2   ┆ 1   ┆ 8.0 │
└─────┴─────┴─────┴─────┘

我想我可以通过使用

['TGT', 'IT', 'Cd']
将第一个数据帧加入分组数据帧上来实现此目的,然后删除双倍的行,因为我只想要每对
'SRC'
一对(和任何)一个
('TGT', 'IT')
。但我想知道是否有更直接的方法来做到这一点,特别是在
'SRC'
 期间保留 
group_by

提前致谢

python python-polars
1个回答
2
投票
import polars as pl

# Your data
data = {
    "SRC": [1, 2, 3, 3],
    "TGT": [1, 1, 1, 2],
    "IT": [2, 2, 2, 1],
    "Cd": [3.0, 4.0, 3.0, 8.0]
}

df = pl.DataFrame(data)

# Sort dataframe by 'Cd'
df_sorted = df.sort('Cd')

# Perform the groupby and aggregation
result = (
    df_sorted.groupby(['TGT', 'IT'])
    .agg(
        [
            pl.col('SRC').first().alias('SRC'),
            pl.col('Cd').min().alias('Cd')
        ]
    )
    .select(['SRC', 'TGT', 'IT', 'Cd'])  # to reorder columns
)

print(result)

enter image description here

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