在数据处理中,我们经常需要根据特定条件创建新的数据列。一个常见的场景是,如果某一列的值满足某个条件,新列就取自当前行的另一列值;否则,新列的值需要从其上方(或下方)最近的满足条件的行中获取。这种“依赖于相邻行”的逻辑,尤其是在存在连续多行不满足条件时,如果采用传统的循环或简单的移位操作,往往效率低下且难以正确处理。
例如,考虑以下DataFrame:
import pandas as pd data = { 'Colonne 1': ['MTN_LI2', 'MTN_IRU', 'MTN_ACE', 'MTN_IME', 'RIPP7', 'CA_SOT', 'CA_OTI', 'CNW00', 'BSNTF', 'RIPNJ'], 'Dimension 1': ['Indicator', 'Indicator', 'Indicator', 'Indicator', 'Organisation', 'Indicator', 'Indicator', 'Organisation', 'Organisation', 'Organisation'] } df = pd.DataFrame(data) print(df)
原始DataFrame df 如下所示:
Colonne 1 Dimension 1 0 MTN_LI2 Indicator 1 MTN_IRU Indicator 2 MTN_ACE Indicator 3 MTN_IME Indicator 4 RIPP7 Organisation 5 CA_SOT Indicator 6 CA_OTI Indicator 7 CNW00 Organisation 8 BSNTF Organisation 9 RIPNJ Organisation
我们的目标是创建一列 new,其逻辑如下:
Pandas提供了Series.where()方法,它允许我们根据布尔条件选择性地保留或替换Series中的值。结合bfill()(backward fill,向后填充)或ffill()(forward fill,向前填充)方法,可以优雅地解决上述问题。
首先,我们使用 Series.where() 来实现条件赋值。where(cond, other=NaN) 的作用是:当 cond 为 True 时,保留原Series的值;当 cond 为 False 时,替换为 other(默认为 NaN)。
对于我们的问题,条件是 df['Dimension 1'].eq('Organisation')。我们希望当条件为真时,取 df['Colonne 1'] 的值。
# 步骤1: 应用 Series.where() temp_series = df['Colonne 1'].where(df['Dimension 1'].eq('Organisation')) print(temp_series)
执行上述代码后,temp_series 将会是:
0 NaN 1 NaN 2 NaN 3 NaN 4 RIPP7 5 NaN 6 NaN 7 CNW00 8 BSNTF 9 RIPNJ Name: Colonne 1, dtype: object
可以看到,所有 Dimension 1 不是 'Organisation' 的行都被替换成了 NaN。
现在,temp_series 中包含了我们需要的“标记”值(即'Organisation'对应的Colonne 1值)以及大量的 NaN。我们需要根据这些标记值来填充 NaN。
使用 bfill() 实现需求:
df['new'] = df['Colonne 1'].where(df['Dimension 1'].eq('Organisation')).bfill() print(df)
输出结果:
Colonne 1 Dimension 1 new 0 MTN_LI2 Indicator RIPP7 1 MTN_IRU Indicator RIPP7 2 MTN_ACE Indicator RIPP7 3 MTN_IME Indicator RIPP7 4 RIPP7 Organisation RIPP7 5 CA_SOT Indicator CNW00 6 CA_OTI Indicator CNW00 7 CNW00 Organisation CNW00 8 BSNTF Organisation BSNTF 9 RIPNJ Organisation RIPNJ
可以看到,RIPP7 成功地填充了其上方的 NaN,CNW00 填充了其上方的 NaN。这完美地解决了问题。
使用 ffill() 的替代方案(了解其不同行为):
如果你的需求是“如果 Dimension 1 的值不是 'Organisation',则 new 列取其上方最近的、Dimension 1 为 'Organisation' 的行的 Colonne 1 值”,那么应该使用 ffill():
df_ffill = df.copy() # 创建副本以展示不同结果 df_ffill['new_ffill'] = df_ffill['Colonne 1'].where(df_ffill['Dimension 1'].eq('Organisation')).ffill() print(df_ffill)
输出结果:
Colonne 1 Dimension 1 new_ffill 0 MTN_LI2 Indicator NaN 1 MTN_IRU Indicator NaN 2 MTN_ACE Indicator NaN 3 MTN_IME Indicator NaN 4 RIPP7 Organisation RIPP7 5 CA_SOT Indicator RIPP7 6 CA_OTI Indicator RIPP7 7 CNW00 Organisation CNW00 8 BSNTF Organisation BSNTF 9 RIPNJ Organisation RIPNJ
注意,使用 ffill() 时,前四行(索引0-3)因为在它们上方没有 'Organisation' 值,所以仍然是 NaN。这突出了 bfill() 和 ffill() 在填充方向上的根本区别。
通过结合 Series.where() 和 Series.bfill() 或 Series.ffill(),我们能够高效且优雅地解决Pandas中涉及条件性赋值和跨行依赖的复杂数据转换问题。这种方法是处理此类场景的推荐实践。
以上就是使用Pandas创建依赖于条件和相邻行值的列的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号