Django0602
Django0602

Reputation: 807

Shuffle pandas columns

I have the following data frame:

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

and I would like to have a shuffled output like :

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

How to achieve this?

Upvotes: 1

Views: 53

Answers (1)

jezrael
jezrael

Reputation: 862711

Use DataFrame.sample with axis=1:

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

If need last column not changed position:

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

Upvotes: 1

Related Questions