logo
down
shadow

How to update value in ndarray by index that is inside another array


How to update value in ndarray by index that is inside another array

By : amit prajapati
Date : November 21 2020, 04:01 AM
Hope this helps Use a one dimensional array for r and use it as the column index. For row indexes you can simply use a range:
code :
In [25]: r=np.random.randint(0, 7, 10)

In [26]: x=np.zeros( (10,7) )

In [27]: x[np.arange(10), r] = 1

In [28]: x
Out[28]: 
array([[0., 1., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 1.],
       [0., 0., 0., 0., 0., 0., 1.],
       [0., 1., 0., 0., 0., 0., 0.],
       [0., 0., 1., 0., 0., 0., 0.],
       [0., 0., 0., 1., 0., 0., 0.],
       [0., 0., 0., 0., 1., 0., 0.],
       [0., 0., 1., 0., 0., 0., 0.],
       [0., 0., 1., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0., 0., 0.]])


Share : facebook icon twitter icon
How do `ndarray.flags['OWNDATA']`, `ndarray.base`, `id(ndarray)` and `ndarray.__array_interface__['data']` differ?

How do `ndarray.flags['OWNDATA']`, `ndarray.base`, `id(ndarray)` and `ndarray.__array_interface__['data']` differ?


By : MrR23
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Most of your confusion comes from the fact that test2 is test and test3 is a view of test.
ndarray.base
code :
>>> import numpy
>>> x = numpy.arange(5)
>>> y = x[1:]
>>> z = x[:-1]
>>> x.__array_interface__['data']
(39692208L, False)
>>> y.__array_interface__['data']
(39692212L, False)
>>> z.__array_interface__['data']
(39692208L, False)
Why using an array as an index changes the shape of a multidimensional ndarray?

Why using an array as an index changes the shape of a multidimensional ndarray?


By : Lift
Date : March 29 2020, 07:55 AM
it helps some times As @hpaulj mentioned in the comments, this behaviour is because of mixing basic slicing and advanced indexing:
code :
a = np.arange(120).reshape(4,5,3,2)
b = a[:,[1,2,3,4,0],:,0]
ndarray row-wise index of values greater than array

ndarray row-wise index of values greater than array


By : Kristaps Leitėns
Date : March 29 2020, 07:55 AM
wish help you to fix your issue You could start by checking which row indices are lower or equal than n and use argmax to get the first True for each row. For the rows where all columns are False, we can use np.where to set them to np.nan for instance:
code :
M = np.array([[1,2,3,4,5],
 [6,7,8,9,1],
 [2,5,7,8,3]])

n = np.array([[3],[7],[100]])

le = n<=M

# array([[False, False,  True,  True,  True],
#        [False,  True,  True,  True, False],
#        [False, False, False, False, False]])

lea = le.argmax(1)
has_any = le[np.arange(len(le)), lea]
np.where(has_any, lea, np.nan)
# array([ 2.,  1., nan])
Any numpy/torch style to set value given an index ndarray and a flag ndarray?

Any numpy/torch style to set value given an index ndarray and a flag ndarray?


By : user3277447
Date : March 29 2020, 07:55 AM
Does that help You may sort flags according to the indices to create a mask, then use the mask as a mux. Here is an example code:
code :
indices = np.array([[2, 1, 3, 0], [1, 0, 3, 2]])
flags = np.array([[False, False, False, True], [False, False, True, True]])
tensor = np.array([[2.8, 0.5, 1.2, 0.9], [3.1, 2.8, 1.3, 2.5]])

indices_sorted = indices.argsort(axis=1)
mask = np.take_along_axis(flags, indices_sorted, axis=1)
result = tensor * (1 - mask) + 1e-30 * mask
Filling the diagonals of square matrices inside a 3D ndarray with values given by a 2D ndarray

Filling the diagonals of square matrices inside a 3D ndarray with values given by a 2D ndarray


By : user3285844
Date : March 29 2020, 07:55 AM
To fix this issue Given a 3D ndarray z with shape (k,n,n), is it possbile without using iteration to fill the diagonals of the k nxn matrices with values given by a 2D ndarray v with shape (k,n)? , Here's for generic n-dim arrays -
code :
diag_view = np.einsum('...ii->...i',z)
diag_view[:] = v
n = v.shape[-1] 
z.reshape(-1,n**2)[:,::n+1] = v.reshape(-1,n)
# or z.reshape(z.shape[:-2]+(-1,))[...,::n+1] = v
m = np.eye(n, dtype=bool) # n = v.shape[-1] from earlier
z[...,m] = v
Related Posts Related Posts :
  • Play sounds in a loop from a list
  • requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://accounts.spotify.com/api/token
  • Pycharm Professional with WSL: Cannot read environment variables set with ~/.profile
  • Choose single float from a list
  • Painter draw RoundedRect inside another Rectangular
  • Finding numbers who digits ^ (digit position) == original number i.e. (89 = 8^1 + 9^2), but the code won't return anythi
  • Mock a python function that is used by another function
  • Selecting values from lists to be put in graphs
  • Less Memory-intense way of copying tables & renaming columns in sqlite/pandas
  • I'm trying to compute the sum of an alphanumeric list
  • using normal distribution and CSV in python
  • convert 2d integer Array to a string separated by commas python
  • LDAP Query Filter User's with Groups Like *x*
  • remove all characters aside from the decimal numbers immediately followed by the £ sign
  • AWS Sagemaker, InvokeEndpoint operation, Model error: "setting an array element with a sequence."
  • Trying to merge all text files in a folder and append file as well
  • How to get JSON into Pandas dataframe with windows authentication
  • Raspberry Pi ---- Reading Rockwell .dbf files
  • Flask App-Builder and many to many relation?
  • my Rect stays for 1 frame created in 'for in' loop Pygame
  • dataframe values multiply by 2
  • python multicolored background
  • unicode argument expected, got 'str'
  • Flask-Misaka can't recognize fenced code in markdown strings
  • Color mapping of data on a date vs time plot
  • read numerical value from file and place it as an array
  • Python unittesting: adding test methods dynamically?
  • Why Pygame only plays the last sound?
  • Conceptual Question : Python Modules, & File Imports, Importing functions from other files
  • Conditional replacing - Python
  • Partial collision between an object
  • 'int' object has no attribute 'ljust'
  • Fill in empty value in a dataframe column with the same value if it already exists in another row
  • Vectorizing string formatting across NumPy array
  • how to integrate a whole click cli module with setuptools entry_points
  • Pythonic way set variables if none in __init__
  • Python remove duplicate entries from list within a list
  • I'm trying to perform certain pattern matching using python's re module
  • Format Google Calendar Event Date
  • How to remove apostrophe's when writing to csv file in Python
  • How to graph the second derivatives of coupled non-linear second order ODEs in Python?
  • Full gradient descent in keras
  • How to manually calculate AUC of the ROC?
  • Python http.server command gives "Syntax Error"
  • How to groupby and sum if the cell value of certain columns fit specific conditions
  • Batch file not closed after being created and written to by Python?
  • Adding an extra in column into 2D numpy array python
  • Scraping content using pyppeteer in association with asyncio
  • Rearrange rows of Dataframe alternatively
  • Function not returning value due to errors in if else logic
  • Value Error in Python while calling a function
  • Is it possible to check if a function is decorated inside another function?
  • How to change "style property" in pygtk2
  • how to create new dataframe out of columns after resampling?
  • Why doesn't this Python code work? It returns no output
  • Python - Split multiple columns into multiple rows
  • Pyinstaller 3.4 Not Working on Windows 10 with Python 2.7
  • inputing numpy array images into pytorch neural net
  • Creating a Dataframe of Proportions
  • Scrapy with dynamic captcha
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org