在数据处理过程中,我们经常需要根据dataframe中某一列或多列的条件来生成新的列。更复杂的情况是,新列的值不仅取决于当前行的条件,还可能依赖于其上方或下方的行的值。例如,当某一行的特定条件不满足时,我们可能希望新列继承其上方或下方最近一个满足条件的行的值。传统的循环方法在处理大型数据集时效率低下,而pandas提供了更高效的向量化操作来实现这一目标。
Pandas中的Series.where()方法允许我们根据布尔条件选择性地替换Series中的值。当条件为False时,对应位置的值将被替换为NaN(默认行为),而当条件为True时,原值保持不变。结合使用Series.bfill()(backward fill,向后填充)或Series.ffill()(forward fill,向前填充)可以巧妙地处理行间依赖关系。
假设我们有一个DataFrame df,包含 Colonne 1 和 Dimension 1 两列。我们的目标是创建一个新列 new,其规则如下:
以下是示例DataFrame:
import pandas as pd import numpy as np 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("原始DataFrame:") print(df)
原始DataFrame:
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
如果需求是当 Dimension 1 不是 'Organisation' 时,新列的值应取其下方最近一个 Dimension 1 为 'Organisation' 的行的 Colonne 1 值,我们可以使用 Series.bfill()。
df['new_bfill'] = df['Colonne 1'].where(df['Dimension 1'].eq('Organisation')).bfill() print("\n使用 bfill() 的结果:") print(df)
解释:
输出结果:
Colonne 1 Dimension 1 new_bfill 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
如果需求是当 Dimension 1 不是 'Organisation' 时,新列的值应取其上方最近一个 Dimension 1 为 'Organisation' 的行的 Colonne 1 值,我们可以使用 Series.ffill()。
df['new_ffill'] = df['Colonne 1'].where(df['Dimension 1'].eq('Organisation')).ffill() print("\n使用 ffill() 的结果:") print(df)
解释:
输出结果:
Colonne 1 Dimension 1 new_bfill new_ffill 0 MTN_LI2 Indicator RIPP7 NaN 1 MTN_IRU Indicator RIPP7 NaN 2 MTN_ACE Indicator RIPP7 NaN 3 MTN_IME Indicator RIPP7 NaN 4 RIPP7 Organisation RIPP7 RIPP7 5 CA_SOT Indicator CNW00 RIPP7 6 CA_OTI Indicator CNW00 RIPP7 7 CNW00 Organisation CNW00 CNW00 8 BSNTF Organisation BSNTF BSNTF 9 RIPNJ Organisation RIPNJ RIPNJ
注意事项:
通过巧妙地结合 Series.where() 和 Series.bfill() / Series.ffill(),我们可以在Pandas中高效地创建依赖于行间关系的条件列。这种方法不仅代码简洁,而且在处理大规模数据时表现出卓越的性能,是Pandas数据操作中非常实用的技巧。理解其工作原理,可以帮助我们解决各种复杂的条件赋值和数据填充问题。
以上就是Pandas中基于条件和行间依赖创建新列的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号