根据多个条件分配值

时间:2019-02-07 15:52:19

标签: python pandas numpy

我的数据框如下:

     timestamp        price       amount amount_f status    eth_amount
0   2018-11-30 13:48:00 0.00348016  10  0   cancelled   0.000000
1   2018-11-30 13:48:00 0.00350065  10  0   cancelled   0.000000
2   2018-11-30 13:50:00 0.00348021  10  0   cancelled   0.000000
3   2018-11-30 13:50:00 0.00350064  10  0   cancelled   0.000000
4   2018-11-30 13:51:00 0.00348054  10  0   cancelled   0.000000
5   2018-11-30 13:51:00 0.00349873  10  0   cancelled   0.000000
6   2018-11-30 13:52:00 0.00348094  10  10  filled  0.034809
7   2018-11-30 13:52:00 0.00349692  10  0   cancelled   0.000000

我实际上需要基于列amountamount_f的值来修改colmun状态。它将是一个if语句,如下所示:

  
      
  • df.amount == df.amount_f then df.status = filled

  •   
  • elif df.amount_f == 0 then df.status = cancelled

  •   
  • else df.status = partially_filled

  •   

我该怎么办?

1 个答案:

答案 0 :(得分:4)

您可以为此使用np.select,这使您可以根据条件列表的结果从值列表(choicelist)中进行选择:

c1 = df.amount == df.amount_f
c2 = df.amount_f == 0
df.loc[:, 'status'] = np.select(condlist=[c1, c2], 
                                choicelist=['filled', 'cancelled'], 
                                default='partially_filled')

        timestamp        price     amount  amount_f  status    eth_amount
0 2018-11-30  13:48:00  0.003480      10         0  cancelled    0.000000
1 2018-11-30  13:48:00  0.003501      10         0  cancelled    0.000000
2 2018-11-30  13:50:00  0.003480      10         0  cancelled    0.000000
3 2018-11-30  13:50:00  0.003501      10         0  cancelled    0.000000
4 2018-11-30  13:51:00  0.003481      10         0  cancelled    0.000000
5 2018-11-30  13:51:00  0.003499      10         0  cancelled    0.000000
6 2018-11-30  13:52:00  0.003481      10        10     filled    0.034809
7 2018-11-30  13:52:00  0.003497      10         0  cancelled    0.000000