Home > other >  Shuffling an array every run in Python
Shuffling an array every run in Python

Time:10-01

In this code, I am trying to shuffle an array r2 using np.random.shuffle() and save it in CSV format in multiple folders with every run. But it doesn't actually shuffle. I don't know why. I also present the current output.

import os
import csv
import numpy as np

Runs=2

r2=np.array([[54.3817864 , 53.42810469, 47.94544424, 53.63511598, 49.59728558,
        49.6935623 , 50.70031442, 52.80854701, 50.18808714, 51.80017684,
        51.85747597, 54.3817864 ]])

def function(run):
    parent_folder = str(run   1)
    os.mkdir(parent_folder)

    
    with open(os.path.join(parent_folder, rf"Inv_Radius_220ND.csv"), 'w ') as f: 
      np.random.shuffle(r2)
      print(f'{run}:{r2}')
      writer = csv.writer(f)
      writer.writerows(r2)
      
for x in range(Runs):
    function(x)      

The current output is

0:[[54.3817864  53.42810469 47.94544424 53.63511598 49.59728558 49.6935623
  50.70031442 52.80854701 50.18808714 51.80017684 51.85747597 54.3817864 ]]
1:[[54.3817864  53.42810469 47.94544424 53.63511598 49.59728558 49.6935623
  50.70031442 52.80854701 50.18808714 51.80017684 51.85747597 54.3817864 ]]

CodePudding user response:

np.random.shuffle(r2) is shuffling the 1st dimension of a two-dimensional array. Since the 1st dimension only contains one array, there's nothing to shuffle.

This should do what you want:

>>> r2
array([[54.3817864 , 53.42810469, 47.94544424, 53.63511598, 49.59728558,
        49.6935623 , 50.70031442, 52.80854701, 50.18808714, 51.80017684,
        51.85747597, 54.3817864 ]])
>>> np.random.shuffle(r2[0])
>>> r2
array([[47.94544424, 54.3817864 , 50.18808714, 49.6935623 , 49.59728558,
        50.70031442, 52.80854701, 51.85747597, 53.42810469, 53.63511598,
        54.3817864 , 51.80017684]])
  • Related