How to randomly shuffle a populaiton by preserving all properites except one?

一世执手 提交于 2020-04-07 08:23:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!