0

When I am using pandas dataframe, I usually need to do this operation:

x.eq(0).sum()/((x.eq(0)&x.shift().ne(0)).sum())

However, I need to work with arrays, and perform this same function.

I noticed that:

x.eq(0).sum()

Can be written like this in numpy:

np.count_nonzero(x == 0)

This second part ((x.eq(0)&x.shift().ne(0)).sum()), I don't know which numpy function substitutes shift().

How to write this function ((x.eq(0)&x.shift().ne(0)).sum()) on numpy ?

William
  • 512
  • 5
  • 17

1 Answers1

0

IIUC:

The shift idea comes from Shift elements in a numpy array

from scipy.ndimage.interpolation import shift

x.eq(0) -> x==0
x.shift() -> shift(x, 1, cval=1)
x.ne(0) -> x!=0

And thus:

((x.eq(0)&x.shift().ne(0)).sum()) -> np.sum(np.logical_and((x==0),shift(x, 1, cval=np.nan)!=0))

Finally:

x.eq(0).sum()/((x.eq(0)&x.shift().ne(0)).sum()) -> np.count_nonzero(x == 0)/np.sum(np.logical_and((x==0),shift(x, 1, cval=1)!=0))

But if I where you, I would just do:

x = pd.Series(x)
Bruno Mello
  • 4,448
  • 1
  • 9
  • 39