# ndarray数组变换

`1 import numpy as np`

## 维度变换

```1 a = np.arange(24)
2 a```
```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])```

reshape(),视图，不修改原数组

`1 a.reshape(4,6)`
```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]])```

`1 a.reshape(2,3,4)`
```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]]])```

`1 a`
```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])```

resize() 修改原数组

`1 a.resize(2,3,4)`
`1 a`
```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]]])```

`1 a.flatten()`
```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])```

# 类型变换

```1 b = np.array([True,20,177.7])
2 b,b.dtype```
`(array([  1. ,  20. , 177.7]), dtype(‘float64‘))`

```1 # 定义数组时修改类型
2 np.array([True,20,177.7],dtype=np.int)```
`array([  1,  20, 177])`

```1 #调用数组时修改类型  #并不改变原数组
2 b
3 b.astype(np.int) #改变视图```
`array([  1,  20, 177])`

`1 b.astype(np.unicode_)`
`array([‘1.0‘, ‘20.0‘, ‘177.7‘], dtype=‘<U32‘)`

`1 b`
`array([  1. ,  20. , 177.7])`

ndarray数组变换

(0)
(0)

0条

© 2014 bubuko.com 版权所有 鲁ICP备09046678号-4