1

A peculiar issue, what is wrong in this code, when the if condition hits the code crashes. This is the original code not in python but converting this to python code

efratio=noise!=0 ? signal/noise : 1

Background of the stockdata is nothing but dataframe value in pandas array. the array list has noise value when I compare this with !=0 in Python I don't know why the program crashes.

Should I use numpy here as this dataframe has the list of data series?

    if (stockdata['noise']!= 0):
        stockdata['efratio']= (stockdata['signal']/stockdata['noise'])
    else :
        stockdata['efratio']= 1

    or
   stockdata['efratio']= (stockdata['signal']/stockdata['noise']) if (stockdata['noise']!= 0) else 1

Edit1: The exception coming is

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

Marx Babu
  • 750
  • 3
  • 11
  • 34

2 Answers2

1

Change:

if (stockdata['noise']!= 0):
        stockdata['efratio']= (stockdata['signal']/stockdata['noise'])
else :
    stockdata['efratio']= 1
    

to:

import numpy as np

stockdata['efratio'] = np.where(stockdata['noise'] != 0,
                                stockdata['signal'] / stockdata['noise'], 1)

This what happens:

where(condition, [x, y])

Return elements, either from x or y, depending on condition.

Community
  • 1
  • 1
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • the same kind of error in this line of code as well coming ,anything to be modified stockdata['kama'] = stockdata['kama'](-1) if stockdata['kama'][-1] !=0 else stockdata['close'] + stockdata['smooth']*(stockdata['close'] - stockdata['kama'](-1) if stockdata['kama'](-1) !=0 else stockdata['close']) – Marx Babu Feb 17 '18 at 10:20
  • Does my solution fix your original error? – Mike Müller Feb 17 '18 at 10:21
  • checked the solution provided by you it is working ! what shall be the fix for the issue given in comment.thank you – Marx Babu Feb 17 '18 at 10:34
  • It is really difficult to read code in a comment. Best would be to ask a new question providing a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – Mike Müller Feb 17 '18 at 10:36
  • it is given in this stackoverflow post ,pleas check and support /48838354/python-equivalent-function-logic-for-nonzero-value-calculation – Marx Babu Feb 17 '18 at 10:41
0

Maybe something like this:

import pandas as pd

stockdata = pd.DataFrame({'noise': [10, 4, 0], 'signal': [1, 2, 3]})

logic = stockdata['noise'] != 0
stockdata['efratio'] = 1.0

stockdata['efratio'][logic] = stockdata['signal'][logic] / (stockdata['noise'][logic])
spadarian
  • 1,604
  • 10
  • 14