exchanging data two python

  python two exchanging data in two ways:

  The first: exchanging data in two in numpy;

  On the code:

1 import numpy as np
2 a = np.array([[1,2,3],[4,5,6]])
3 >>> a
4 array([[1, 2, 3],
5        [4, 5, 6]])
6 >>> a[:,[0, -1]] = a[:,[-1, 0]]
7 >>> a
8 array([[3, 2, 1],
9        [6, 5, 4]])

  The second: exchanging data in two pandas; u.data to movieLen100K in Example;

  On the code:

   

 1 import pandas as pd
 2 import numpy as np
 3 
 4 file = 'ml-100k/u.data'
 5 df = pd.read_csv(file, sep='\t', header=None ,names=['a'  , 'b' ,'c' ,'d'])
 6 print(df)
 7 cols = list(df)
 8 cols.insert(2,cols.pop(cols.index('d')))
 9 df = df.loc[:,cols]
10 print(df)

 

  Test Results:

 

         a     b          d  c
0      196   242  881250949  3
1      186   302  891717742  3
2       22   377  878887116  1
3      244    51  880606923  2
4      166   346  886397596  1

  Clearly, 'd' and 'c' exchange position;

  Thus, python finished the data exchange position;

  

Guess you like

Origin www.cnblogs.com/caizhou520/p/12614559.html