Issue
I wanted to retrieve random columns from a numpy array in python. I have retrieved the random rows by using the code given below:
data = [[1,2,3,4],[3,8,9],[5,3,9]]
random_arr = np.random.randint(0,data.shape[1],2)
data[random_arr]
I want the output as
a = [[1,2],
[3,8],
[5,3]]
or
a = [[3,5],
[8,3],
[9,9]]
Solution
The code sample you provided doesn't even run... So here is how you can do both:
Extract random rows:
import numpy as np
data = np.array([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
])
num_rows_to_extract = 2
random_indices = np.random.choice(data.shape[0], num_rows_to_extract, replace=False)
random_rows = data[random_indices]
print("Random Rows:")
print(random_rows)
Extract random columns:
import numpy as np
data = np.array([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
])
num_cols_to_extract = 2
num_columns = data.shape[1]
random_indices = np.random.choice(num_columns, num_cols_to_extract, replace=False)
random_columns = data[:, random_indices]
print("Random Columns:")
print(random_columns)
Please provide full examples like this if you want people to focus on the problem, not the question.
Answered By - Geom
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.