python - Pandas 根据其他列的条件进行分组求和

标签 python pandas

我有以下数据框:

df = pd.DataFrame({'Position':['Entry','Partial','Partial','Partial','Entry','Partial','Partial','Entry','Partial'],
               'Symbol':['AA','AA','AA','AA','BB','BB','BB','CC','CC'],
               'Action':['Sell','Buy','Buy','Buy','Buy','Sell','Sell','Sell','Buy'],
               'Quantity':['4','2','1','1','2','1','1','1','1'],
               'Price':['2.1','1.5','2.2','1','4.6','5.1','4.5','1','1.1']})

enter image description here

我正在尝试在另一列中计算每个唯一符号的损益。该值取决于入场的方向,以确定利润是否等于卖出 - 买入值(value)或买入 - 卖出值(value)。我很难弄清楚如何将这些值求和到下一个交易品种/入场指标。

我的尝试包括使用 numpy.where 函数以及 dataframe.assign 函数。有人可以帮助我理解如何解决这些基于条件的求和问题吗?

我正在尝试如下输出,其中我将唯一的符号字符串及其相对损益输出保留下来。

Expected Output

最佳答案

确切的预期输出尚不清楚,但假设您需要一个新列来总结每个符号的买卖:

# ensure we have numeric values and not strings
df[['Quantity', 'Price']] = df[['Quantity', 'Price']].apply(pd.to_numeric)

df['profit/loss'] = (df['Action']
 .map({'Buy': -1, 'Sell': 1})    # make Buy -1 and Sell 1
 .mul(df['Price'])               # make Buy negative values
 .mul(df['Quantity'])            # multiply by Quantity
 .groupby(df['Symbol'])
 .transform('sum')               # sum per group as new column
)

输出:

  Position Symbol Action  Quantity  Price  profit/loss
0    Entry     AA   Sell         4    2.1          2.2
1  Partial     AA    Buy         2    1.5          2.2
2  Partial     AA    Buy         1    2.2          2.2
3  Partial     AA    Buy         1    1.0          2.2
4    Entry     BB    Buy         2    4.6          0.4
5  Partial     BB   Sell         1    5.1          0.4
6  Partial     BB   Sell         1    4.5          0.4
7    Entry     CC   Sell         1    1.0         -0.1
8  Partial     CC    Buy         1    1.1         -0.1

如果您不需要新专栏而是摘要:

(df['Action']
 .map({'Buy': -1, 'Sell': 1})
 .mul(df['Price']).mul(df['Quantity'])
 .groupby(df['Symbol']).sum()
)

输出:

Symbol
AA    2.2
BB    0.4
CC   -0.1
dtype: float64

关于python - Pandas 根据其他列的条件进行分组求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73889948/

相关文章:

python - 如何从 tkinter 中的 excel 值中下拉?

python - 如何将所有数组的元素添加到python中的一个列表中

Python - JSON模块代码中没有参数的构造函数

python - nlargest(2) 在行级别检索列名称和相等值

python - Pandas,根据数据间隔创建列值

python - Pandas 到 sql server

python - Python 3.4 中多线程如何工作?

python - Python 中的函数给出错误消息

python - 填充 NaN 值

python - 将 DTM 转换为文本