问题
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.
回答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.
回答2:
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.
来源:https://stackoverflow.com/questions/60687700/how-to-randomly-shuffle-a-populaiton-by-preserving-all-properites-except-one