Valentyn
Valentyn

Reputation: 612

How to shuffle each column of pandas dataframe?

For example, my text file looks like

John Smith 19 
Alex Greelish 89
Sandra Alexandru 44

How can I shuffle each column? Example of expected result:

Sandra Greelish 44
Alex Smith 19
John Alexandru 89

Currently, my code looks in the following way:

import pandas as pd
df = pd.read_csv('test.txt', sep=" ", header=None)
print(df.sample(frac=1))

Upvotes: 1

Views: 188

Answers (1)

jezrael
jezrael

Reputation: 863611

Use DataFrame.apply with convert to numpy array for prevent index alignement:

df = df.apply(lambda x: x.sample(frac=1).to_numpy())

Upvotes: 2

Related Questions