How to randomly shuffle a populaiton by preserving

2020-05-04 11:09发布

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.

2条回答
神经病院院长
2楼-- · 2020-05-04 11:42

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.

查看更多
Bombasti
3楼-- · 2020-05-04 11:46

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.

查看更多
登录 后发表回答