维小维写作训练营python学习笔记

python:numpy之数组转置

2019-08-13  本文已影响0人  书生_Scholar

首先导入numpy,并生成数组

In [1]:import numpy as np
In [2]:t2 = np.arange(24).reshape(4,6)
In [3]:t2
# t2的输出为:
Out[3]: 
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23]])\
In [4]:t2.T                                    # 转置方式一
Out[4]: 
array([[ 0,  6, 12, 18],
       [ 1,  7, 13, 19],
       [ 2,  8, 14, 20],
       [ 3,  9, 15, 21],
       [ 4, 10, 16, 22],
       [ 5, 11, 17, 23]])
In [5]:t2.transpose()                         # 转置方式二
Out[85]: 
array([[ 0,  6, 12, 18],
       [ 1,  7, 13, 19],
       [ 2,  8, 14, 20],
       [ 3,  9, 15, 21],
       [ 4, 10, 16, 22],
       [ 5, 11, 17, 23]])
In [9]:t2.swapaxes(1, 0)                   # 转置方式三,“交换轴“
Out[9]: 
array([[ 0,  6, 12, 18],
       [ 1,  7, 13, 19],
       [ 2,  8, 14, 20],
       [ 3,  9, 15, 21],
       [ 4, 10, 16, 22],
       [ 5, 11, 17, 23]])

4、第四种方法

# coding=utf-8
import numpy as np

us_path = "./data/us.csv"
uk_path = "./data/uk.csv"

# 载入csv数据
us_data = np.loadtxt(us_path, delimiter=",", dtype="int", unpack=True)  # unpack=True代表转置
uk_data = np.loadtxt(uk_path, delimiter=",", dtype="int")

print(us_data)
print("*" * 100)
print(uk_data)
########输出的结果如下#########
C:\ProgramData\Anaconda3\python.exe D:/ssslll/programe/PycharmProjects/Study/us_uk_data.py
[[ 38999411   9667808  36445855 ...  82531293  72610963 155305748]
 [ 12597031  46983244  35706526 ... 154917371 182245183 209305602]
 [       38        26        46 ...         6        12       177]
 [      724      2059      2989 ...      5996      8310      1648]]
****************************************************************************************************
[[ 38999411  12597031        38       724]
 [  9667808  46983244        26      2059]
 [ 36445855  35706526        46      2989]
 ...
 [ 82531293 154917371         6      5996]
 [ 72610963 182245183        12      8310]
 [155305748 209305602       177      1648]]

Process finished with exit code 0

上一篇下一篇

猜你喜欢

热点阅读