Shuffle Columns in Dataframe

Viewed 1104

I want to shuffle columns without order; completely pseudo-randomly, on one line of code.

Before:

  A B
0 1 2
1 1 2

After:

  B A
0 2 1
1 2 1

My attempts so far:

df = df.reindex(columns=columns)

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

df.apply(np.random.shuffle, axis=1)
3 Answers

You can use np.random.default_rng()'s permutation with a seed to make it reproducible.

df = df[np.random.default_rng(seed=42).permutation(df.columns.values)]

Use DataFrame.sample with the axis argument set to columns (1):

df = df.sample(frac=1, axis=1)
print(df)
   B  A
0  2  1
1  2  1

Or use Series.sample with columns converted to Series and change order of columns by subset:

df = df[df.columns.to_series().sample(frac=1)]
print(df)
   B  A
0  2  1
1  2  1
Related