随机排列的熊猫列

问题描述 投票:0回答:1

我有以下数据框:

    Col1  Col2  Col3  Type
0      1     2     3     1
1      4     5     6     1
2      7     8     9     2

而且我希望有一个像这样的混排输出:

        Col3  Col1  Col2  Type
    0      3     1     2     1
    1      6     4     5     1
    2      9     7     8     2

如何实现?

python-3.x pandas shuffle
1个回答
1
投票

用途:

df = df.sample(frac=1, axis=1)

如果需要的类型总是在最后:

a = df.columns[:-1].to_numpy()
np.random.shuffle(a)
print (a)
['Col3' 'Col1' 'Col2']

df = df[np.append(a, ['Type'])]
print (df)
   Col2  Col3  Col1  Type
0     3     1     2     1
1     6     4     5     1
2     9     7     8     2
© www.soinside.com 2019 - 2024. All rights reserved.