logo
down
shadow

Making 2 dimensional numpy array with two 1 dimensional array


Making 2 dimensional numpy array with two 1 dimensional array

By : Mahesh Kaushik
Date : November 21 2020, 04:01 AM
I hope this helps you . I would like to convert 2 numpy arrays such as these ones: , This is a job for meshgrid and stack:
code :
a = np.array([ [1, 2, 3] ])
b = np.array([ [100, 200, 300] ])

print(np.stack(np.meshgrid(a, b)).T.reshape(-1,2))


Share : facebook icon twitter icon
In numpy, what is the fastest way to multiply the second dimension of a 3 dimensional array by a 1 dimensional array?

In numpy, what is the fastest way to multiply the second dimension of a 3 dimensional array by a 1 dimensional array?


By : ShammyLevva
Date : March 29 2020, 07:55 AM
hope this fix your issue Use broadcasting:
code :
A*B[:,np.newaxis]
In [47]: A=np.arange(24).reshape(2,3,4)

In [48]: B=np.arange(3)

In [49]: A*B[:,np.newaxis]
Out[49]: 
array([[[ 0,  0,  0,  0],
        [ 4,  5,  6,  7],
        [16, 18, 20, 22]],

       [[ 0,  0,  0,  0],
        [16, 17, 18, 19],
        [40, 42, 44, 46]]])
Making comparisons of a m-dimensional array and an (m-1)-dimensional array repeated along an arbitrary dimension

Making comparisons of a m-dimensional array and an (m-1)-dimensional array repeated along an arbitrary dimension


By : pedroparra
Date : March 29 2020, 07:55 AM
this one helps. Assuming that you meant (I'm assuming this because otherwise m3d - m2d.z.3d doesn't work):
code :
m3d = outer(m2d, items3, "*") # note how I switched the arguments
m3d - c(m2d)
all.equal(m3d - c(m2d), m3d - m2d.z.3d)
# [1] TRUE
funOuter <- function() {
  m2d.z.3d = outer(
    m2d, 
    rep(1, length(items3)), "*"
  )
  m3d - m2d.z.3d
}
funRecycle <- function() m3d - c(m2d)
funLoop <- function() apply(m3d, 3, "-", m2d)    # this does not appear correct because `apply` doesn't reconstruct dimensions like `sapply`
funSweep <- function() sweep(m3d, c(1, 2), m2d)  # this is the same type of thing but works properly

library(microbenchmark)
microbenchmark(funOuter(), funRecycle(), funLoop(), funSweep())
Unit: milliseconds
         expr       min        lq      mean    median
   funOuter()  2.297287  2.673768  3.232277  2.835404
 funRecycle()  1.327101  1.485082  2.093252  1.599543
    funLoop() 22.579010 24.586667 27.211804 26.840069
   funSweep() 11.251656 12.012664 13.516147 13.736908       
all.equal(funOuter(), funRecycle())
# [1] TRUE
all.equal(funOuter(), funSweep())
# [1] TRUE
all.equal(funOuter(), funLoop())
# Nope, not equal
Extracting portions of low-dimensional numpy array into final axes of higher-dimensional array

Extracting portions of low-dimensional numpy array into final axes of higher-dimensional array


By : Katarzyna Leszczyńsk
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further One way would be with np.meshgrid to create 2D indexing meshes corresponding to the window of (n,n) shape, adding those with i0 that's extended with two new axes along which broadcasting would take place. Finally, we simply index into C to give us the desired 4D output. Thus, one implementation would be like so -
code :
N = np.arange(n)
X,Y = np.meshgrid(N,N)
out = C[i0[...,None,None] + Y,i0[...,None,None] + X]
In [153]: C
Out[153]: 
array([[3, 5, 1, 6, 3, 5, 8, 7, 0, 2],
       [8, 4, 6, 8, 7, 2, 6, 2, 5, 0],
       [3, 7, 7, 7, 3, 4, 4, 6, 7, 6],
       [7, 0, 8, 2, 1, 1, 0, 4, 4, 6],
       [2, 4, 6, 0, 0, 5, 6, 8, 0, 0],
       [4, 6, 1, 0, 5, 6, 2, 1, 7, 4],
       [0, 5, 5, 3, 7, 5, 7, 1, 4, 0],
       [6, 4, 4, 7, 2, 4, 6, 6, 6, 5],
       [5, 2, 3, 2, 2, 5, 4, 5, 2, 5],
       [3, 7, 1, 0, 4, 4, 6, 6, 2, 2]])

In [154]: i0
Out[154]: 
array([[1, 0, 4, 4],
       [0, 4, 4, 0],
       [2, 3, 1, 3],
       [2, 2, 0, 4]])

In [155]: n = 3

In [157]: out[0,0,:,:]
Out[157]: 
array([[4, 6, 8],
       [7, 7, 7],
       [0, 8, 2]])

In [158]: C[i0[0,0]:i0[0,0]+n,i0[0,0]:i0[0,0]+n]
Out[158]: 
array([[4, 6, 8],
       [7, 7, 7],
       [0, 8, 2]])
Construction of two dimensional numpy array from unequally shaped one dimensional arrays | Numpy

Construction of two dimensional numpy array from unequally shaped one dimensional arrays | Numpy


By : user621459
Date : March 29 2020, 07:55 AM
I wish this help you In python have three one dimensional arrays of different shapes (like the ones given below) , You can use numpy stack functions to speed up:
code :
aa = [a0, a1, a2]
np.hstack(tuple(np.vstack((np.full(ai.shape, i), ai)) for i, ai in enumerate(aa))).T
Convert multi-dimensional Numpy array to 2-dimensional array based on color values

Convert multi-dimensional Numpy array to 2-dimensional array based on color values


By : sutenm
Date : March 29 2020, 07:55 AM
To fix the issue you can do You could use giant lookup table. Let cls be [[0,0,0], [0,0,255], ...] of dtype=np.uint8.
code :
LUT = np.zeros(size=(256,256,256), dtype='u1')
LUT[cls[:,0],cls[:,1],cls[:,2]] = np.arange(cls.shape[1])+1
img_as_cls = LUT[img[...,0],img[...,1], img[...,2]]
def scalarize(x):
    # compute x[...,2]*65536+x[...,1]*256+x[...,0] in efficient way
    y = x[...,2].astype('u4')
    y <<= 8
    y +=x[...,1]
    y <<= 8
    y += x[...,0]
    return y
LUT = np.zeros(2**24, dtype='u1')
LUT[scalarize(cls)] = 1 + np.arange(cls.shape[0])
simg = scalarize(img)
img_to_cls = LUT[simg]
Related Posts Related Posts :
  • Decompose string of different symbols in python
  • pandas merge and group concat
  • How to traverse tree for making binary code from a HuffmanTree?
  • Check if IP is in network on Python3
  • non equally spaced points along x-axis in a plot
  • Concatenation of text files consisting list of lists?
  • Use regex to parse characters on a line of text
  • pandas df.fillna - filling NaNs after outer join with correct values
  • How can I undo a time series conversion of a pandas dataframe?
  • Virtual environment is not working in Django
  • FileNotFoundError in Python during Arabic text analysis
  • How to read email using python and smtplib
  • How to write a function which takes a string and turns into a single digit?
  • Linear Regression without Least Squares in sklearn
  • Matplotlib - Box plot with number of occurrence of data?
  • Finding the numbers in a given range who have a perfect square for the sum of their divisors and returning them with the
  • How do I put y(a) and y(b) initial conditions in odeint(python) instead of y(0) and y'(0)?
  • Import Error in Tensorflow in Jupyter Notebook
  • How to convert a mapping of ranges into a dictionary
  • lxml scraping overwrite error due to missing element
  • How can I run different codes from different editor tabs on the Spyder on the same console (as opposed to different tabs
  • urllib3 connectionpool - Connection pool is full, discarding connection
  • How to change django-filter filtering key?
  • Python Google Sheets API Limit 429 Error with Loop
  • How can I turn this DataFrame into a DataFrame with average score by Index Value?
  • summing element in a range for all element in an array
  • pm2 json file format for python script
  • Mask dataframe column based on datetime index
  • Brute force stable marriage, How to implements all possible pairs between 2 lists?
  • Rounding hours of datetime in PySpark
  • Show data only from one cluster
  • ValueError: Cannot feed value of shape (64,) for Tensor 'x:0', which has shape '(?, 128, 128, 1)'
  • Python try except not working with np.arccos
  • Grouping by and Combining the Strings
  • python threading.local() in different module
  • Or keyword for pandas series
  • Python Django using wsgi.py with apache2 loads filter fields out of order every restart
  • Using FireStore in Google Dataflow
  • Filter a DataFrame By Date One Week Previous From Current Date
  • How to transpose pandas dataframe to cross-tabulate dataframe keeping all values
  • How best way to transform one list into new list with pairs of elements from list?
  • Conditionals in numpy. How can i put 3 or more into my dataframe using pandas or numpy?
  • Failed to specific gcc version when setup python
  • LSTM hyperparameters not available in model.summary() after loading model
  • creating pandas-vectorized 'subtraction' table
  • Python configuration in Windows - Module locations - pip vs Eclipse/Liclipse
  • CUDA_ERROR_INVALID DEVICE with keras=2.0.5 and tensorflow-gpu=1.2.1
  • Is it safe to use next within a for loop in Python?
  • PORTING usage of s3curl.pl to Python
  • How to install Python 3.5.5?
  • Python 3.7 - PIP upgrade error on windows 10
  • How can I fix this function?
  • Optimizing execution time for appending data (Python)
  • Why my Depth function returns the Height of Binary tree not the depth?
  • How to access values of a class from a different method(out the class)
  • Groupby to create new columns
  • Fabric - ThreadingGroup exception stops remaining requests?
  • Timezone conversion with pyspark from timestamp and country
  • I want to create a table and select the value using row and column using python
  • Extract data from a span with BeautifulSoup
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org