Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 874
curious_one Avatar asked Jun 20 '17 10:06

curious_one


Video Answer


2 Answers

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
like image 156
jezrael Avatar answered Oct 23 '22 08:10

jezrael


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
like image 20
MSeifert Avatar answered Oct 23 '22 06:10

MSeifert