0

A spherical region of space is filled with a specific distribution of smaller, different size spheres. Each sphere is associated with some physical properties: position, radius, mass, velocity, and ID all represented as 1d or 3d numpy arrays. I would like to shuffle this population of spheres in a totally random manner such that any single sphere preserves all of its properties except its 3d position array. I have encountered this similar question in here (Randomly shuffle columns except first column) but, is there an easy and fast pythonic way to do this without using DataFrame?

Thank for your help.

Rebel
  • 472
  • 8
  • 25

2 Answers2

1

You can implement a Knuth shuffle (https://en.wikipedia.org/wiki/Random_permutation), its quite straight-forward.

You can adapt the implementation algorithm to only swap your desired properties.

  • Thank you. That page is in C language. Unfortunately, I am not familiar with C. But, I will try to understand it. – Rebel Mar 14 '20 at 22:30
  • here is the format of the column before [[ -36.12 -51.06 222.9 ] [-211.2 21.56 215.1 ] [-215.3 -36.88 175.9 ] ... [ 181.9 53.9 185.1 ] [ 145.1 156.4 159. ] [ -16.59 11.52 165.8 ]] and here is its format after the shuffle [list([9.32, 6.92, -9.669]) list([67.61, 116.6, 35.13]) list([149.4, 107.3, 159.8]) ... list([79.3, -44.27, 0.03649]) list([19.0, -13.63, -16.86]) list([140.0, -177.1, 104.0])]. Can you help me fixe it in a way that I get the same format afterwards? – Rebel Mar 18 '20 at 01:40
1

If you're using pandas, you could just shuffle one column:

df['col'] = df['col'].sample(frac=1).values

This works equally well on any subset of columns, e.g.

cols = ['col1', 'col2']
df[cols] = df[cols].sample(frac=1).values

The two columns are shuffled together, i.e. their respective values remain aligned.

See also this answer.

Kris
  • 22,079
  • 3
  • 30
  • 35
  • Thank you Kris, what if I want to shuffle two columns simultaneously meaning the corresponding values of any row remain together as we shuffle the columns? – Rebel Mar 27 '20 at 03:53
  • @Ash Have a look at the updated answer. Is that what you had in mind? – Kris Mar 31 '20 at 02:20