python交换数据的两列,python处理excel数据,  python交换


  python交换数据的两列有两种方式:

  第一种:在numpy中交换数据的两列;

  上代码:

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

  第二种:在pandas中交换数据的两列;以movieLen100K中的u.data为例;

  上代码:

  

 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)

  测试结果:

         a     b          d  c0      196   242  881250949  31      186   302  891717742  32       22   377  878887116  13      244    51  880606923  24      166   346  886397596  1

  很明显,‘d’与‘c’交换了位置;

  至此,python中的数据交换位置讲完;

  

python交换数据的两列

评论关闭