Polars基本操作 - context

在Polars中,上下文(context)操作是一种按组进行数据处理的方法。它允许您在每个组内对数据进行选择(selection)、过滤(filtering)和聚合(Group by / Aggregation)。

1. 选择(selection)

import polars as pl

# 创建一个DataFrame
df = pl.DataFrame({
    'group': ['A', 'A', 'B', 'B', 'A'],
    'value': [1, 2, 3, 4, 5],
    'count': [10, 20, 30, 40, 50]
})

# 选择group和value两列
result = df.select(['group', 'value'])

print(result)

2. 过滤(filtering)

import polars as pl

# 创建一个DataFrame
df = pl.DataFrame({
    'group': ['A', 'A', 'B', 'B', 'A'],
    'value': [1, 2, 3, 4, 5]
})

# 在每个组内过滤掉小于3的值
result = df.groupby('group').apply(lambda x: x.filter(pl.col('value') >= 3))

print(result)

3. 聚合(Group by / Aggregation)

import polars as pl

# 创建一个DataFrame
df = pl.DataFrame({
    'group': ['A', 'A', 'B', 'B', 'A'],
    'value': [1, 2, 3, 4, 5]
})

# 在每个组内计算平均值和总和
result = df.groupby('group').agg({'value': ['mean', 'sum']})

print(result)

与之相对比的pandas的选择、过滤和聚合

1. pandas选择(IMHO,比Polars的简单)

import pandas as pd

# 创建一个DataFrame
df = pd.DataFrame({
    'group': ['A', 'A', 'B', 'B', 'A'],
    'value': [1, 2, 3, 4, 5],
    'count': [10, 20, 30, 40, 50]
})

# 选择group和value两列
result = df[['group', 'value']]

print(result)

2. pandas过滤(可以用布尔索引过滤)

import pandas as pd

# 创建一个DataFrame
df = pd.DataFrame({
    'group': ['A', 'A', 'B', 'B', 'A'],
    'value': [1, 2, 3, 4, 5]
})

# 在每个组内过滤掉小于3的值
result = df.groupby('group').apply(lambda x: x[x['value'] >= 3])

print(result)

3. pandas聚合

import pandas as pd

# 创建一个DataFrame
df = pd.DataFrame({
    'group': ['A', 'A', 'B', 'B', 'A'],
    'value': [1, 2, 3, 4, 5]
})

# 在每个组内计算平均值和总和
result = df.groupby('group')['value'].agg(['mean', 'sum'])

print(result)

IMHO,看起来context操作,Pandas比Polars更直观。不过Polars能处理的数据量比Pandas大。

  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值