• python交换数据的两列


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

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

      上代码:

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

      第二种:在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='	', 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  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

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

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

      

  • 相关阅读:
    JDK6和JDK7中的substring()方法
    考试结束
    今天之总结
    暂别
    珍惜
    放弃
    我男神
    心态
    稳住,我或许能赢
    还是做好自己吧
  • 原文地址:https://www.cnblogs.com/caizhou520/p/12614559.html
Copyright © 2020-2023  润新知