how to randomly sample in 2D matrix in numpy

2024/9/19 22:43:01

I have a 2d array/matrix like this, how would I randomly pick the value from this 2D matrix, for example getting value like [-62, 29.23]. I looked at the numpy.choice but it is built for 1d array.

The following is my example with 4 rows and 8 columns

Space_Position=[[[-62,29.23],[-49.73,29.23],[-31.82,29.23],[-14.2,29.23],[3.51,29.23],[21.21,29.23],[39.04,29.23],[57.1,29.23]],[[-62,11.28],[-49.73,11.28],[-31.82,11.28],[-14.2,11.28],[3.51,11.28],[21.21,11.28] ,[39.04,11.28],[57.1,11.8]],[[-62,-5.54],[-49.73,-5.54],[-31.82,-5.54] ,[-14.2,-5.54],[3.51,-5.54],[21.21,-5.54],[39.04,-5.54],[57.1,-5.54]],[[-62,-23.1],[-49.73,-23.1],[-31.82,-23.1],[-14.2,-23.1],[3.51,-23.1],[21.21,-23.1],[39.04,-23.1] ,[57.1,-23.1]]]

In the answers the following solution was given:

random_index1 = np.random.randint(0, Space_Position.shape[0])
random_index2 = np.random.randint(0, Space_Position.shape[1])
Space_Position[random_index1][random_index2]

this indeed works to give me one sample, how about more than one sample like what np.choice() does?

Another way I am thinking is to tranform the matrix into a array instead of matrix like,

Space_Position=[[-62,29.23],[-49.73,29.23],[-31.82,29.23],[-14.2,29.23],[3.51,29.23],[21.21,29.23],[39.04,29.23],[57.1,29.23], .....   ]

and at last use np.choice(), however I could not find the ways to do the transformation, np.flatten() makes the array like

Space_Position=[-62,29.23,-49.73,29.2, ....]
Answer

Just use a random index (in your case 2 because you have 3 dimensions):

import numpy as npSpace_Position = np.array(Space_Position)random_index1 = np.random.randint(0, Space_Position.shape[0])
random_index2 = np.random.randint(0, Space_Position.shape[1])Space_Position[random_index1, random_index2]  # get the random element.

The alternative is to actually make it 2D:

Space_Position = np.array(Space_Position).reshape(-1, 2)

and then use one random index:

Space_Position = np.array(Space_Position).reshape(-1, 2)      # make it 2D
random_index = np.random.randint(0, Space_Position.shape[0])  # generate a random index
Space_Position[random_index]                                  # get the random element.

If you want N samples with replacement:

N = 5Space_Position = np.array(Space_Position).reshape(-1, 2)                # make it 2D
random_indices = np.random.randint(0, Space_Position.shape[0], size=N)  # generate N random indices
Space_Position[random_indices]  # get N samples with replacement

or without replacement:

Space_Position = np.array(Space_Position).reshape(-1, 2)  # make it 2D
random_indices = np.arange(0, Space_Position.shape[0])    # array of all indices
np.random.shuffle(random_indices)                         # shuffle the array
Space_Position[random_indices[:N]]  # get N samples without replacement
https://en.xdnf.cn/q/72182.html

Related Q&A

How to update figure in same window dynamically without opening and redrawing in new tab?

I am creating a 3D scatter plot based off a pandas dataframe, and then I want to re-draw it with slightly updated data whenever the user presses a button in my program. I almost have this functionality…

Serializing a C struct in Python and sending over a socket

Im trying to serializing the following C structstruct packet {int id;unsigned char *ce;unsigned char *syms; };in Python and send it over a socket. The number of elements pointed by ce and syms are know…

creating multiple audio streams of an icecast2 server using python-shout

I am trying to create a web radio server to stream 3 sources at once. I am using python to create a source client for icecast2 using the python-shout library. I am not too familiar with the language (p…

Custom Deployment to Azure Websites

I recently started using Gulp.js to package all my CSS and JavaScript into single files, which I then include in my web app. My web app is written in Python (using Flask).I obviously dont want to track…

Python - Gspread Request Error 401

Im currently making a Discord-bot that connects to a Google-spreadsheet (gspread). But after Ive been running it for a while it starts to hand out errors and it cant connect to my gspread anymore (unle…

paramiko server mode port forwarding

I need to implement a ssh server using paramiko that only handles -R port forwarding requests like this:ssh -N -T -R 40005:destination_host:22 [email protected]So far from what i understand ill have to…

Pandas dataframe.hist() change title size on subplot?

I am manipulating DataFrame using pandas, Python. My data is 10000(rows) X 20(columns) and I am visualizing it, like this.df.hist(figsize=(150,150))However, if I make figsize bigger, each of subplots t…

Regex match back to a period or start of string

Id like to match a word, then get everything before it up to the first occurance of a period or the start of the string. For example, given this string and searching for the word "regex":s = …

Finding differences between strings

I have the following function that gets a source and a modified strings, and bolds the changed words in it.def appendBoldChanges(s1, s2):"Adds <b></b> tags to words that are changed&qu…

Python pandas: select 2nd smallest value in groupby

I have an example DataFrame like the following:import pandas as pd import numpy as np df = pd.DataFrame({ID:[1,2,2,2,3,3,], date:array([2000-01-01,2002-01-01,2010-01-01,2003-01-01,2004-01-01,2008-01-01…