基于分组和条件添加新列:Pandas教程

碧海醫心
发布: 2025-08-07 21:02:32
原创
1050人浏览过

基于分组和条件添加新列:pandas教程

本文详细介绍了如何使用 Pandas 在 DataFrame 中基于分组和条件添加新列。通过 groupby()、apply()、sort_values()、shift() 和 cumsum() 等函数的组合使用,可以实现复杂的数据转换和列生成。本文提供清晰的代码示例和详细的步骤解释,帮助读者理解并掌握该技巧,从而解决实际数据处理中的类似问题。

在数据分析和处理中,经常需要在 Pandas DataFrame 中基于现有列进行分组,并根据分组内的条件计算新列的值。本教程将详细介绍如何使用 Pandas 实现这一目标,并通过一个具体的例子进行说明。

示例数据

首先,我们创建一个示例 DataFrame,用于演示如何添加新列:

import pandas as pd
import numpy as np

data = {
    'id': [1, 2, 3, 4, 5, 6, 7],
    'date': ['2019-02-01', '2019-02-10', '2019-02-25', '2019-03-05', '2019-03-16', '2019-04-05', '2019-05-15'],
    'date_difference': [None, 9, 15, 11, 10, 19, 40],
    'number': [1, 0, 1, 0, 0, 0, 0],
    'text': ['A', 'A', 'A', 'A', 'A', 'B', 'B']
}

df = pd.DataFrame(data)
print(df)
登录后复制

问题描述

我们的目标是基于 text 列进行分组,并根据 number 列的值生成一个新的列 test。对于每个分组,test 列的值的计算规则如下:

  1. 首先按照 date 列降序排列组内数据。
  2. 如果 number 列的值为 0,则 test 列的值从 1 开始递增。
  3. 如果在 number 列中出现 1,则后续的 test 列的值在之前的最大值基础上保持不变。
  4. 如果分组内没有 1,则 test 列的值始终为 1。

解决方案

以下代码展示了如何使用 Pandas 实现上述逻辑:

硅基智能
硅基智能

基于Web3.0的元宇宙,去中心化的互联网,高质量、沉浸式元宇宙直播平台,用数字化重新定义直播

硅基智能 62
查看详情 硅基智能
import pandas as pd


data = {
    'id': [1, 2, 3, 4, 5, 6, 7],
    'date': ['2019-02-01', '2019-02-10', '2019-02-25', '2019-03-05', '2019-03-16', '2019-04-05', '2019-05-15'],
    'date_difference': [None, 9, 15, 11, 10, 19, 40],
    'number': [1, 0, 1, 0, 0, 0, 0],
    'text': ['A', 'A', 'A', 'A', 'A', 'B', 'B']
}

df = pd.DataFrame(data)

out = df.assign(
    # We assign the following values to the series name "test"
    test=df
    # Group on "text" -- if we grouped on ["text", "number"] we wouldn't see different numbers within the groups.
    .groupby("text")
    # Apply a chain of methods to the group (a pd.DataFrame).
    .apply(
        lambda g: (
            # We sort "date" in descending order as you mention this partially controls the step size.
            g.sort_values(by="date", ascending=False)
            # We shift "number" forward one period with a fill_value of 1 for any newly introduced nulls.
            .number.shift(periods=1, fill_value=1)
            # Cumulatively sum the shifted "number" values
            .cumsum()
        )
        # This will result in the new series, albeit sorted by descending "date".
    )
    # Drop the "text" level of the new multi-index.
    .droplevel("text")
    # The assign method acts as join, rearranging the newly created series to match the index of `df`.
)
print(out)
登录后复制

代码解释:

  1. df.groupby("text"): 首先,我们使用 groupby() 函数按照 text 列对 DataFrame 进行分组。
  2. .apply(lambda g: ...): 然后,我们使用 apply() 函数对每个分组应用一个自定义的 lambda 函数。
  3. g.sort_values(by="date", ascending=False): 在 lambda 函数内部,我们首先按照 date 列降序排列每个分组。
  4. .number.shift(periods=1, fill_value=1): 使用 shift() 函数将 number 列的值向前移动一位。fill_value=1 用于填充移动后产生的缺失值,保证第一行数据的值为 1。
  5. .cumsum(): 使用 cumsum() 函数计算移动后的 number 列的累积和,从而得到 test 列的值。
  6. .droplevel("text"): 删除分组后产生的MultiIndex,确保结果与原DataFrame的索引对齐。
  7. df.assign(test=...): 最后,使用 assign() 函数将新生成的 test 列添加到原始 DataFrame 中。

总结

本教程介绍了如何使用 Pandas 在 DataFrame 中基于分组和条件添加新列。通过 groupby()、apply()、sort_values()、shift() 和 cumsum() 等函数的组合使用,可以灵活地实现复杂的数据转换和列生成。理解并掌握这些技巧,可以帮助您更高效地进行数据分析和处理。

注意事项:

  • 在实际应用中,需要根据具体的数据和需求调整代码。
  • 理解每个函数的具体作用和参数,才能更好地应用它们。
  • 可以使用其他 Pandas 函数和方法来进一步优化代码,例如 fillna()、where() 等。

以上就是基于分组和条件添加新列:Pandas教程的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号