gpt4 book ai didi

python - 按组随机播放 Pandas 数据框

转载 作者:太空宇宙 更新时间:2023-11-03 14:04:05 24 4
gpt4 key购买 nike

我的数据框是这样的

sampleID  col1 col2
1 1 63
1 2 23
1 3 73
2 1 20
2 2 94
2 3 99
3 1 73
3 2 56
3 3 34

我需要将相同样本放在一起的数据帧进行洗牌,并且 col1 的顺序必须与上述数据帧中的顺序相同。

所以我需要这样的

sampleID  col1 col2
2 1 20
2 2 94
2 3 99
3 1 73
3 2 56
3 3 34
1 1 63
1 2 23
1 3 73

我该怎么做?如果我的示例不清楚,请告诉我。

最佳答案

假设您想按 sampleID 进行随机播放。先df.groupby,shuffle(先import random),然后调用pd.concat:

import random

groups = [df for _, df in df.groupby('sampleID')]
random.shuffle(groups)

pd.concat(groups).reset_index(drop=True)

sampleID col1 col2
0 2 1 20
1 2 2 94
2 2 3 99
3 1 1 63
4 1 2 23
5 1 3 73
6 3 1 73
7 3 2 56
8 3 3 34

您可以使用 df.reset_index(drop=True) 重置索引,但这是一个可选步骤。

关于python - 按组随机播放 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45585860/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com