logo
down
shadow

Python Numpy: Coalesce and return first nonzero observation


Python Numpy: Coalesce and return first nonzero observation

By : Caio César
Date : November 20 2020, 11:01 PM
Hope that helps "Coalesce": use putmask to replace values equal to zero with values from array2:
code :
want = array1.copy()
np.putmask(array1.copy(), array1==0, array2)
where_nonzero = np.where(np.tril(want) != 0)

"""For the where array, get the indices of only 
the first index for each column"""
first_indices = np.unique(where_nonzero[1], return_index=True)[1]

# Get the values from want for those indices
want2 = want[(where_nonzero[0][first_indices], where_nonzero[1][first_indices])]


Share : facebook icon twitter icon
Explanation of python code snippet >>numpy.nonzero(row == max(row))[0][0]<< from a script using numpy

Explanation of python code snippet >>numpy.nonzero(row == max(row))[0][0]<< from a script using numpy


By : GalS
Date : March 29 2020, 07:55 AM
will be helpful for those in need What does this peace of python code , Perhaps an example will help:
code :
In []: R= arange(12).reshape(4, 3)
In []: R
Out[]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])
In []: i= 1
In []: row= R[i, ]
In []: row
Out[]: array([3, 4, 5])
In []: j= nonzero(row== max(row))[0][0]
In []: j
Out[]: 2
In []: R[i, j]
Out[]: 5
Nonzero function help, Python Numpy

Nonzero function help, Python Numpy


By : user3357592
Date : March 29 2020, 07:55 AM
hop of those help? I have two arrays, and I have a complex condition like this: new_arr<0 and old_arr>0 I am using nonzero but I am getting an error. The code I have is this: , Try indices = nonzero((new_arr < 0) & (old_arr > 0)):
code :
In [5]: import numpy as np

In [6]: old_arr = np.array([ 0,-1, 0,-1, 1, 1, 0, 1])

In [7]: new_arr = np.array([ 1, 1,-1,-1,-1,-1, 1, 1])

In [8]: np.nonzero((new_arr < 0) & (old_arr > 0))
Out[8]: (array([4, 5]),)
Python Numpy nonzero

Python Numpy nonzero


By : user1989575
Date : March 29 2020, 07:55 AM
I wish did fix the issue. This may be due to the fact that len(X) only returns X's length along the first axis. When you do
code :
X = X[np.nonzero(X)]
In [1]: import numpy as np

In [2]: X = np.zeros((42, 2))

In [3]: X[:, 0] = 1

In [4]: X[0, 1] = 1

In [5]: len(X)
Out[5]: 42

In [6]: len(X[np.nonzero(X)])
Out[6]: 43
In [7]: X[np.nonzero(X)].shape
Out[7]: (43,)
X = X[ X[:, 0] != 0 ]
Python / Cython / Numpy optimization of np.nonzero

Python / Cython / Numpy optimization of np.nonzero


By : user2531088
Date : March 29 2020, 07:55 AM
I wish this helpful for you Jaime may have given a good answer, but I will comment on improving the Cython code and add a performance comparison.
First, you should use the 'annotate' feature, cython -a filename.pyx, this will generate an HTML file. Load that in a browser and it highlights 'slow' lines with yellow-orange, this indicates where improvements can be made.
code :
        for xDiff in [-1,0,1]:
            for yDiff in [-1,0,1]:
                for zDiff in [-1,0,1]:
        for xDiff in range(-1, 2):
            for yDiff in range(-1, 2):
                for zDiff in range(-1, 2):
                            if array[x1,y1,z1]:
def sphericity(np.ndarray[np.uint8_t, ndim=3] array):
    cdef np.uint8_t array_view [:, :, :] = array
    ...
                                    if array_view[x1,y1,z1]:
    for x in range(0, xSize):
        for y in range(0, ySize):
            for z in range(0, zSize):
                if array[x,y,z] == 0:
                    continue
                ... 
#cython: boundscheck=False, nonecheck=False, wraparound=False
import numpy as np
cimport numpy as np

def sphericity2(np.uint8_t [:, :, :] array):

    #Pass an mask array (1's are marked, 0's ignored)
    cdef int xSize,ySize,zSize
    xSize=array.shape[0]
    ySize=array.shape[1]
    zSize=array.shape[2]

    cdef int sa,vol,x,y,z,neighbors,xDiff,yDiff,zDiff,x1,y1,z1
    cdef float onethird,twothirds,sp
    sa=vol=0 #keep running tally of volume and surface area

    for x in range(0, xSize):
        for y in range(0, ySize):
            for z in range(0, zSize):
                if array[x,y,z] == 0:
                    continue

                neighbors=0
                vol+=1

                for xDiff in range(-1, 2):
                    for yDiff in range(-1, 2):
                        for zDiff in range(-1, 2):
                            if abs(xDiff)+abs(yDiff)+abs(zDiff)==1:
                                x1=x+xDiff
                                y1=y+yDiff
                                z1=z+zDiff
                                if x1>=0 and y1>=0 and z1>=0 and x1<xSize and y1<ySize and z1<zSize:
                                    #print '-',x1,y1,z1,array[x1,y1,z1]
                                    if array[x1,y1,z1]:
                                        #print '-',x1,y1,z1,array[x1,y1,z1]
                                        neighbors+=1

                #print 'had this many neighbors',neighbors
                sa+=(6-neighbors)

    onethird=float(1)/float(3)
    twothirds=float(2)/float(3)
    sph = ((np.pi**onethird)*((6*vol)**twothirds)) / sa
    #print 'sphericity',sphericity
    return sph
Original         : 2.123s
Jaime's          : 1.819s
Optimized Cython : 0.136s
@ moarningsun    : 0.090s
Python numpy nonzero cumsum

Python numpy nonzero cumsum


By : Θεοδωρος Παντος
Date : March 29 2020, 07:55 AM
To fix the issue you can do I want to do nonzero cumsum with numpy array. Simply skip zeros in array and apply cumsum. Suppose I have a np. array , Just trying to simplify it:)
code :
b=np.cumsum(a)
[b[i]  if ((i > 0 and b[i] != b[i-1]) or i==0) else 0 for i in range(len(b))]
Related Posts Related Posts :
  • Is it possible to make pygame work with a slightly newer version of python?
  • to show the weights of edges in a projected network
  • as the missing method of QTabWidget of this code is written?
  • Python - return multiple values using tuple (AWS lambda function)
  • How can I get the text use xpath from the text?
  • Python generator function - is there an excel equivalent?
  • Pandas: fastest way to resolve IP to country
  • Saving huge amount of data (nearly 20 billion entries) in django postgresql
  • Is there a difference between != and <> operators in Python?
  • How to move pointer to specific bytes and read using Pickle Library in Python?
  • Create 2-d array with column keys and row keys in Python
  • Detect match failure in JMESPath
  • python3 django1.8 mysql5.5 gives page not found (404) while sqlite works fine
  • Django forms: List of checkboxes populated from a model
  • Deploying django static files in production
  • How to find the alignment of two data sets in pandas
  • antlr4 + python: debug token match
  • How to 'blit' sprites onto window for a set time
  • Program that checks if a number is prime number
  • python pandas time line graph
  • Reading a text file with OpenCV in Python
  • PyGame in MacOSX: CGContextDrawImage: invalid context 0x0
  • Twisted chat server demo exits immediately
  • How to calculate block averages in pandas DataFrame
  • how to change a list to a specific string.
  • Overlapping text when saving multiple Matplotlib images with text in a loop
  • How do I scrape ONLY <div class ='quotetext'> from a website using python?
  • Python: Float Object is not Iterable
  • ValueError: need more than 3 values to unpack
  • Evaluate while loop at certain point?
  • RxPy - Why are emissions interleaved with merging operators?
  • Spyder - hints disappear too fast
  • Creating a |N| x |M| matrix from a hash-table
  • daily data, resample every 3 days, calculate over trailing 5 days efficiently
  • How to do this program without a counter?
  • Saving a data frame with a column of list in python
  • Python newbie - refactor string function
  • TypeError: deafultdict must have first arguments callable
  • Zero padding not performed properly I think
  • When to bind to attributes that populated with kv-file?
  • Python - Adding "hidden" values to tuples
  • Multselecting in Pandas using .loc
  • python - checking if an array consisting of N integers is a permutation
  • How do you set the outer bg colour of a plot in matplotlib
  • Checking if an input is formatted correctly in Python 3
  • How to restrict two columns not to have the same value using Django?
  • Using turtle in Python to draw six-pointed stars with different side lengths
  • QAbstractListModel does not get updated with values when data is loaded from CSV, but it does when using hardcoded value
  • Python - Modify dictionary from function
  • django-ldap-auth user profile in django > 1.7
  • Rate Limit API Calls to Shopify API with Django on Google App Engine
  • TypeError: decoding str is not supported
  • Regular expression behaves unexpectedly when using some specific words
  • Counting uppercase letters in a list excluding the first capital in a word
  • Use socket.io to display realtime data
  • How to neatly print dictionaries with dictionaries inside
  • sorting dictionary by numeric value
  • How to find HDF5 file groups/keys within Python?
  • Cannot access nested dictionary in python
  • How to add a code fix for infinite loop while adding two integers using bitwise operations
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com