How to transfer one column in pandas

I have a pandas dataframe with 3 columns:

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

      

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

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

      

I only found how to rearrange all columns by re-indexing them, but not how to do it for just one column.

+3


source to share


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

      

+3


source


Just in case, if you don't want a random permutation, and you want to get a certain "permutation", you can always roll

:



>>> 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

      

0


source







All Articles