djl
djl

Reputation: 277

Shuffle portion of rows in DataFrame

I have come across some previous posts regarding how to shuffle row values (Randomizing/Shuffling rows in a dataframe in pandas). For me though, I was wondering how to shuffle a portion of those rows, rather than the entirety of these rows.

I made a quick dataframe here:

df = pd.DataFrame(np.random.randn(10, 5), columns=list('ABCDE'))

Is there a way to re-work this such that for each row, the values in columns B,C,and D are shuffled while the values in columns A and E remain in the same location?

Upvotes: 2

Views: 252

Answers (1)

tfv
tfv

Reputation: 6259

You can use slicing in the shuffle command:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(10, 5), columns=list('ABCDE'))
print df

A=df.values
_= [np.random.shuffle(i) for i in A[: ,1:4]]

df2=pd.DataFrame(A, columns=list('ABCDE'))
print df2

Upvotes: 1

Related Questions