curious_one
curious_one

Reputation: 563

How to permute one column in pandas

I have pandas dataframe with 3 columns:

X1   X2    Y
1    2     1
2    4     0
3    6     1  

I want to permute only one column X1 and the result is:

X1   X2    Y
3    2     1
1    4     0
2    6     1

I only found how permute all columns by reindexing them but not how to do this only for one column.

Upvotes: 10

Views: 9150

Answers (2)

MSeifert
MSeifert

Reputation: 152715

Just in case you don't want a random permutation and you want a specific "permutation" you can always roll columns:

>>> import numpy as np
>>> df['X1'] = np.roll(df['X1'], 1)  # move each item one row down (with wraparound)
>>> df
   X1  X2  Y
0   3   2  1
1   1   4  0
2   2   6  1

Upvotes: 2

jezrael
jezrael

Reputation: 863146

Use numpy.random.permutation:

df['X1'] = np.random.permutation(df['X1'])
print (df)
   X1  X2  Y
0   3   2  1
1   2   4  0
2   1   6  1

Upvotes: 15

Related Questions