遍历数据框并根据列和条件计算数字

时间:2019-03-31 20:10:06

标签: python pandas

我正在尝试解决一个问题,该问题需要我在几次交易后计算公司的预期股份。股份数量将从100开始,然后根据交易是买入还是卖出,计算将加或减。这个问题的一个警告是,如果交易“交易对手”是BnL,则迭代中不应在计算中使用该行。

我要在此处附加数据框的图片:

https://imgur.com/a/ivKjISD

到目前为止,我已经尝试了以下方法,但是在BnL警告方面遇到了很多麻烦:

Quantity_IBM_Crest_822 = 100
for index, row in Quantity_IBM_Crest_822.iterrows():
    if row['Buy/Sell'] == 'B':
        Quantity_IBM_Crest_822 = Quantity_IBM_Crest_822 + row['Quantity']
    else:
        Quantity_IBM_Crest_822 = Quantity_IBM_Crest_822 - row['Quantity']        
print(Quantity_IBM_Crest_822)

3 个答案:

答案 0 :(得分:1)

使用Pandas数据框或序列方法,而不是涉及跨行循环的通用Python:

sub_df = IBM_Crest_822.query("Counterparty != 'BnL Corp.'")

Quantity_IBM_Crest_822 = 100 + sum(sub_df['Buy/Sell'] == "B") + \
                               -1*sum(sub_df['Buy/Sell'] == "S")

答案 1 :(得分:0)

我们需要忽略BnL Corp.交易,因此首先我们可以获取数量将CounterpartyBnL Corp.的值替换为零的数量。然后,每当Buy/SellS时,我们将这些值乘以-1。最后,我们用cumsum计算累计和,并加上初始值100:

df = pd.DataFrame({'Buy/Sell': ['B','B','B','B','S','B','B','B','S','S'],
                   'Quantity': [50, 100, 80, 20, 20, 150, 110, 200, 200, 40],
                   'Counterparty': ['M', 'M', 'BnL Corp.', 'A', 'A', 'BnL Corp.', 'BnL Corp.', 'BnL Corp.', 'M', 'A']})

x = df['Quantity'] * (df['Counterparty'] != 'BnL Corp.')
x.loc[df['Buy/Sell']=='S'] *= -1
df['CumQuantity'] = x.cumsum() + 100

print(df)

输出:

  Buy/Sell  Quantity Counterparty  CumQuantity
0        B        50            M          150
1        B       100            M          250
2        B        80    BnL Corp.          250
3        B        20            A          270
4        S        20            A          250
5        B       150    BnL Corp.          250
6        B       110    BnL Corp.          250
7        B       200    BnL Corp.          250
8        S       200            M           50
9        S        40            A           10

如果您仅对结果数量感兴趣:

x.sum() + 100

输出:

10

注意:这也是总金额的一栏:

100 + sum(df['Quantity']*(2*(df['Buy/Sell']=='B')-1)*(df['Counterparty']!='BnL Corp.'))

输出:

10

答案 2 :(得分:0)

导出一个新的DataFrame,该数据帧不包含Counterparty列中具有BnL的交易。

withoutBnLDf = IBM_Crest_822[IBM_Crest_822['Counterparty'] != 'Bnl Corp.']

此外,在尝试遍历DataFrame的行时,应使用.iterrows()

Quantity_IBM_Crest_822 = 100
for index, row in withoutBnLDf.iterrows():
    if row['Buy/Sell'] == 'B':
        Quantity_IBM_Crest_822 = Quantity_IBM_Crest_822 + row['Quantity']
    else:
        Quantity_IBM_Crest_822 = Quantity_IBM_Crest_822 - row['Quantity']        
print(Quantity_IBM_Crest_822)