David Hancock
David Hancock

Reputation: 1071

Separating positive and negative values of pandas DataFrame

I need to separately sum all positive and negative values in a column ie

pos_values = [x for x in df.prediction_at_ohlcv_end_date if x > 0] 
neg_values = [x for x in df.prediction_at_ohlcv_end_date if x < 0] 

Here's a data sample

market_trading_pair next_future_timestep_return ohlcv_start_date    prediction_at_ohlcv_end_date
0   Poloniex_ETH_BTC    0.003013    1450753200  -0.157053
1   Poloniex_ETH_BTC    -0.006521   1450756800  -0.920074
2   Poloniex_ETH_BTC    0.003171    1450760400  0.999806
3   Poloniex_ETH_BTC    -0.003083   1450764000  0.627140
4   Poloniex_ETH_BTC    -0.001382   1450767600  0.999857

What's a nice way to do this in pandas ?

EDIT:

I have been able to do this thanks to some helpful stackers, I realised I can't a futher calculation however. `

if prediction_at_ohlcv_end_date > 0 : 
return = prediction_at_ohlcv_end_date * next_future_timestep_return. 

For each element in the frame, Any ideas?`

Upvotes: 1

Views: 9576

Answers (1)

Anton Protopopov
Anton Protopopov

Reputation: 31672

You could use method sum of pandas.Series for your particular column:

neg = df.prediction_at_ohlcv_end_date[df.prediction_at_ohlcv_end_date < 0].sum()
pos = df.prediction_at_ohlcv_end_date[df.prediction_at_ohlcv_end_date >= 0].sum()

In [51]: pos
Out[51]: 2.6268029999999998

In [52]: neg
Out[52]: -1.077127

For your values:

pos_values = df.prediction_at_ohlcv_end_date[df.prediction_at_ohlcv_end_date >= 0]
neg_values = df.prediction_at_ohlcv_end_date[df.prediction_at_ohlcv_end_date < 0]

EDIT

For your edit you could do:

mask = df.prediction_at_ohlcv_end_date >= 0
res = df.prediction_at_ohlcv_end_date[mask] * df.next_future_timestep_return[mask]

In [10]: res
Out[10]: 
2    0.003170
3   -0.001933
4   -0.001382
dtype: float64

Upvotes: 3

Related Questions