(Two answers) Last year
I have a matrix list of 100x3 as shown below.
There are two things you would like to do with this matrix:
·I would like to randomly extract two lines at any number of times (e.g., 3 times).
ex)[[a1, a2, a3],
]
[b1, b2, b3]
·I want to change the extracted two rows to become one row and create a matrix of the number of attempts x the set of rows taken out.
[[a1, a2, a3, b1, b2, b3],
[c1, c2, c3, d1, d2, d3],
[e1, e2, e2, f1, f2, f3]
Additional
The first 100x3 matrix treats it as a block of values for one line, or three values.
Can you accomplish the desired operation with the sample code below?
After randomly rearranging an array, you can get any pair from the beginning and combine the arrays with the +
operator.
To another question, Comment can produce similar results more elegantly, so I added it to the sample code.
import string
import random
# create an array from ["a1", "a2", "a3"] to ["z1", "z2", and "z3"] as preparations
arr = [ ]
for cinstring.ascii_lowercase [:26]:
arr.append ([f"{c}{i}"for i in range(1,4)])
# Randomly extract arbitrary lines (3 lines)
count = 3
random.shuffle(arr)# Completely random shuffle
rnd_arr = [ ]
for i in range(0, count*2,2): # take any two lines from the beginning
rnd_arr.append(arr[i]+arr[i+1])# Combine the two lines into one array
print(rnd_arr)
# [[['e1', 'e2', 'e3', 'c1', 'c2', 'c3', ['a1', 'a2', 'a3', 'x1', 'x2', 'x3', ['z1', 'z2', 'z3', 'p1', 'p2', 'p3']]]]]]]] and so on.
# Additional note (number version)
import numpy as np
rnd_nparr=np.random.permission(arr)[0:count*2].reshape(3,6)
print(rnd_nparr)
# [['r1' 'r2' 'r3' e1' e2' e3']
# ['x1' 'x2' 'x3's1's2's3']
# ['m1' 'm2' 'm3' 'b1' 'b2' 'b3']] etc.
© 2024 OneMinuteCode. All rights reserved.