
本文旨在介绍如何使用 Pandas 在满足特定条件下对数据进行累计求和。我们将演示如何基于相邻列(例如,“Buy”和“Sell”)的值来选择性地累加“Value”列,并提供详细的代码示例和解释,帮助读者理解和应用这种数据处理技巧。
在数据分析中,经常需要根据特定条件对数据进行累计求和。Pandas 提供了强大的工具来实现这一目标,而无需编写显式的循环。下面,我们将详细介绍如何利用 Pandas 的 combine_first(), ffill(), 和 cumsum() 函数,基于相邻列的条件来实现累计求和。
首先,我们创建一个 Pandas DataFrame 来模拟实际数据:
import pandas as pd
import numpy as np
df1 = pd.DataFrame({
'date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05', '2023-01-06', '2023-01-07', '2023-01-08', '2023-01-09', '2023-01-10', '2023-01-11', '2023-01-12'],
'buy': [None, 1, None, None, None, None, None, 1, None, None, None, None],
'sell': [None, None, None, None, 1, None, None, None, None, None, 1, None],
'value': [1, 5, 1, 1, 1, 5, 1, 5, 1, 1, 1, 5]
})在这个 DataFrame 中,buy 和 sell 列表示买入和卖出信号,value 列表示需要累计求和的值。我们的目标是仅在 buy 或 sell 列有值时才累加 value。
处理 sell 列: 为了区分 buy 和 sell 信号,我们将 sell 列的值乘以 -1。这有助于后续的条件判断。
df1['sell'] = df1['sell'] * -1
合并 buy 和 sell 列: 使用 combine_first() 函数将 buy 和 sell 列合并成一个新的 buysell 列。如果 buy 列有值,则使用 buy 的值;否则,使用 sell 的值。
df1['buysell'] = df1['buy'].combine_first(df1['sell'])
填充 buysell 列: 使用 ffill() 函数向前填充 buysell 列中的 NaN 值。这会将买入信号延续到下一个非 NaN 值之前。
df1.loc[df1['buysell'].ffill() == 1, 'buysell'] = 1
创建掩码: 创建一个布尔掩码,用于标记 buysell 列中非 NaN 值的行。
mask = ~df1['buysell'].isna()
创建 buysellvalue 列: 使用掩码将 value 列的值复制到新的 buysellvalue 列中,仅针对 buysell 列中非 NaN 值的行。
df1.loc[mask, 'buysellvalue'] = df1.loc[mask, 'value']
累计求和: 使用 cumsum() 函数对 buysellvalue 列进行累计求和,并将结果存储在 cumbuysellvalue 列中。
df1['cumbuysellvalue'] = df1['buysellvalue'].cumsum()
import pandas as pd
import numpy as np
df1 = pd.DataFrame({
'date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05', '2023-01-06', '2023-01-07', '2023-01-08', '2023-01-09', '2023-01-10', '2023-01-11', '2023-01-12'],
'buy': [None, 1, None, None, None, None, None, 1, None, None, None, None],
'sell': [None, None, None, None, 1, None, None, None, None, None, 1, None],
'value': [1, 5, 1, 1, 1, 5, 1, 5, 1, 1, 1, 5]
})
# make sell negative so it can be discerned from buy
df1['sell'] = df1['sell'] * -1
# create 'buysell' column which is combination of 'buy' and 'sell' columns
df1['buysell'] = df1['buy'].combine_first(df1['sell'])
# use ffill() to fill buysell from 1 until it is not 1
df1.loc[df1['buysell'].ffill() == 1, 'buysell'] = 1
# create a mask for where 'buysell' is not NaN
mask = ~df1['buysell'].isna()
# use the mask to create a 'buysellvalue' column with the contents of 'value' column for rows where the mask is true
df1.loc[mask, 'buysellvalue'] = df1.loc[mask, 'value']
# use cumsum()
df1['cumbuysellvalue'] = df1['buysellvalue'].cumsum()
print(df1)通过使用 Pandas 的 combine_first(), ffill(), 和 cumsum() 函数,我们可以高效地实现基于相邻列条件的累计求和,避免了使用循环,提高了代码的执行效率和可读性。这种方法在金融数据分析、时间序列分析等领域非常有用。
以上就是基于相邻列条件进行累计求和的 Pandas 教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号