Close

## Numpy Useful Functions - Create Array Python

Last Updated on Wednesday 5th Oct 2022

## Python Create Array

NumPy provides a variety list of functions for creating arrays.

## np array

### Creating Arrays from Python Sequences

You can create an array from a Python list or tuple by using NumPy’s array function.(2,3 - shaped array)

### numpy sequence

```			```
import numpy as np

print(np.array([[1, 4, 6], [3, 5, 7]]))

```

```
```			```
# [
#  [1 4 6]
#  [3 5 7]
# ]

```

```

### Creating 1 dim array with zeros

NumPy provides the functions zeros and ones, which will fill an array of user-specified shape with `0s` and `1s`.

```			```
import numpy as np

print(np.zeros(5))
print(np.ones(5))

```

```

Output

```			```
[0. 0. 0. 0. 0.]
[1. 1. 1. 1. 1.]

```

```

### Creating new array with 4 rows and 3 columns

`[0]*3` will produce `[0, 0, 0]`.

```			```
import numpy as np

print(np.array([[0*4]*3]))

print(np.array([[0*4]*3]*2))

```

```
```			```
# [
#   [0 0 0]
# ]

# [
#   [0 0 0]
#   [0 0 0]
# ]

```

```

### Generate Array Python

```			```
import numpy as np

print(np.zeros((4, 3)))

```

```

Output

```			```
[
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
]

```

```

### Create a square N × N identity matrix

```			```
import numpy as np

print(np.eye(4))

```

```

Output

```			```
[
[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]
]

```

```

### numpy make array

Several functions can be accessed from `np.random`, which derived arrays randomly.

### Creates uniform random numbers

```			```
import numpy as np

print(np.random.random((2, 2)))

```

```

Output

```			```
[
[ 0.05802877  0.36875017]
[ 0.52098717  0.02762662]
]

```

```

### Creates random integer (from - to)

```			```
import numpy as np

print(np.random.randint(5, 15, (4, 4)))

```

```

Output

```			```
[
[10 14 10  6]
[ 7  6  6  7]
[ 7 11  7 12]
[10  8  7 10]
]

```

```

### numpy create array

```			```
import numpy as np

x = np.array([1, 2, 3])
y = np.array([-1, -2, -3])

print(np.vstack([x, y]))
print(np.hstack([x, y]))

```

```
```			```
# [
#   [ 1  2  3]
#   [-1 -2 -3]
# ]
# [ 1  2  3 -1 -2 -3]

```

```