[TOC]
# 改變數組的維度
~~~
import numpy as np
# 創建0-10包左不包右的數組
tang_array = np.arange(10)
print(tang_array)
print(tang_array.shape)
# 把shape值變為2行5列
tang_array.shape = 2, 5
print(tang_array)
~~~
輸出
~~~
[0 1 2 3 4 5 6 7 8 9]
(10,)
[[0 1 2 3 4]
[5 6 7 8 9]]
~~~
修改shape值會影響原來的值
如果不想影響原來的值
~~~
import numpy as np
# 創建0-10包左不包右的數組
tang_array = np.arange(10)
# reshape操作后結果要接收,不會影響原來的數組
reshape = tang_array.reshape(5, 2)
print(reshape)
~~~
但是我們要注意,分的時候要注意原來數組的個數
~~~
import numpy as np
tang_array = np.arange(10)
reshape = tang_array.reshape(2,3)
print(reshape)
~~~
報錯
~~~
Traceback (most recent call last):
File "/Users/jdxia/Desktop/study/py/study.py", line 5, in <module>
reshape = tang_array.reshape(2,3)
ValueError: cannot reshape array of size 10 into shape (2,3)
~~~
# 新增維度
~~~
import numpy as np
tang_array = np.arange(10)
print(tang_array.shape)
# :表示原來的東西還是要的,newaxis表示增加一個維度
tang_array = tang_array[np.newaxis, :]
print(tang_array)
print(tang_array.shape)
~~~
輸出
~~~
(10,)
[[0 1 2 3 4 5 6 7 8 9]]
(1, 10)
~~~
原來是1維的
新增一個維度變為2維的了
# 壓縮維度
~~~
import numpy as np
tang_array = np.arange(10)
# :表示原來的東西還是要的,newaxis表示增加一個維度
tang_array = tang_array[np.newaxis, :]
print(tang_array)
# 再新增2個維度
tang_array = tang_array[:, np.newaxis, np.newaxis]
print(tang_array)
# 壓縮元素,把空的軸壓縮掉
tang_array = tang_array.squeeze()
print(tang_array.shape)
~~~
輸出
~~~
[[0 1 2 3 4 5 6 7 8 9]]
[[[[0 1 2 3 4 5 6 7 8 9]]]]
(10,)
~~~
# 行列轉換
把原來的行列數轉換下
~~~
import numpy as np
tang_array = np.arange(10)
# 指定壓縮的形狀
tang_array.shape = 2, 5
print(tang_array)
print('-' * 10)
# 也可以寫成這樣tang_array.T,他不改變原來的值
transpose = tang_array.transpose()
print(transpose)
~~~
輸出
~~~
[[0 1 2 3 4]
[5 6 7 8 9]]
----------
[[0 5]
[1 6]
[2 7]
[3 8]
[4 9]]
~~~
# 數組的連接
拼接
~~~
import numpy as np
a = np.array([[123, 345, 567], [43, 23, 45]])
b = np.array([[12, 343, 56], [132, 454, 56]])
# 里面的參數要類似元祖的形式
c = np.concatenate((a, b))
print(c)
~~~
輸出
~~~
[[123 345 567]
[ 43 23 45]
[ 12 343 56]
[132 454 56]]
~~~
還可以指定維度
~~~
import numpy as np
a = np.array([[123, 345, 567], [43, 23, 45]])
b = np.array([[12, 343, 56], [132, 454, 56]])
# 里面的參數要類似元祖的形式(橫著拼接)
c = np.concatenate((a, b), axis=1)
print(c)
~~~
輸出
~~~
[[123 345 567 12 343 56]
[ 43 23 45 132 454 56]]
~~~
**便捷寫法**
~~~
import numpy as np
a = np.array([[123, 345, 567], [43, 23, 45]])
b = np.array([[12, 343, 56], [132, 454, 56]])
# 橫著拼接
hstack = np.hstack((a, b))
print(hstack)
# 豎著拼接
vstack = np.vstack((a, b))
print(vstack)
~~~
# 拉平
~~~
import numpy as np
a = np.array([[123, 345, 567], [43, 23, 45]])
flatten = a.flatten()
print(flatten)
~~~
輸出
~~~
[123 345 567 43 23 45]
~~~