# How to Create a NumPy Array in Python?

NumPy module in Python is a powerful library that is used extensively in data manipulation and scientific computing. In this article, we will look how to create NumPy Arrays and some of its basic attributes.

## What is NumPy?

NumPy, stands for Numerical Python, and it is an open-source library that provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. With NumPy, complex mathematical operations and manipulations can become very easy.

## Creating NumPy Arrays

Arrays are the central data structure of the NumPy library. Let’s look into the process of creating these arrays.

### Creating One-Dimensional Arrays

A one-dimensional array is like a list in Python, but with superpowers. It’s designed to handle numerical computation efficiently. Let’s see an example, where we will create a NumPy Array from a list

```import numpy as np

# Create a Python list
listOfNumbers = [2, 3, 4]

# Convert list to a NumPy array
arr = np.array(listOfNumbers)

# Display the array
print(arr)
```

Output:

```[2 3 4]
```

This code snippet creates a one-dimensional NumPy array from a Python list. We have imported the NumPy module with the alias `np`. So, we can use `np` instead of word `numpy` while accessing the functions.

### Checking the Data Type of NumPy Array

To confirm that we’ve created a NumPy array, we can use the `type()` function:

```print(type(arr))
```
```<class 'numpy.ndarray'>
```

The output will confirm that `arr` is of type `numpy.ndarray`, which stands for ‘n-dimensional array’.

## Creating Two-Dimensional NumPy Arrays

We can also create 2D NumPy arrays, and use them as matrices. Here’s how we can create a 2D array from nested lists:

```# Create a 2D array from a list of lists
arr2D = np.array([[12, 34, 67],
[42, 10,-33],
[11, 12, 22]])

# Display the 2D array
print(arr2D)
```

Output:

```[[ 12  34  67]
[ 42  10 -33]
[ 11  12  22]]
```

In this 2D array, each inner nest list is converted into a row within the NumPy array.

## Data Types in NumPy Arrays

NumPy supports a greater variety of numerical data types than Python does. This is important because the data type determines how the data is stored in memory, how subsequent calculations are performed on that data, and how the data is interpreted when being read. Common data types in NumPy include:

• `int` (e.g., `int16`, `int32`, `int64`)
• `float` (e.g., `float16`, `float32`, `float64`)
• `complex` (e.g., `complex64`, `complex128`)
• `bool`
• `str`
• `object`

### Upcasting of Data Types in NumPy Array

NumPy arrays are homogeneous, which means they strive to have all elements of the same data type only. If you mix data types, NumPy will upcast if possible (e.g., integers will be upcast to floats if floats are present in the list).

If you provide multiple types in a NumPy array, NumPy will automatically upcast the data types to the highest precision present. Here’s an example of upcasting:

```import numpy as np

# Integers and floats are mixed,
# so NumPy upcasts integers to floats
arr1 = np.array([1, 2.5, 4])

print(arr1.dtype)  # Output: float64

# Integers and boolean are mixed,
# So NumPy upcasts boolean to integers
arr2 = np.array([1, False, 3])

print(arr2.dtype)  # Output: int64
```

Output:

```float64
int64
```

### Explicitly Setting the Data Type of NumPy Array

You can explicitly set the type of the array elements using the `dtype` parameter:

```import numpy as np

# Create an array with data type float
arr = np.array([11, 22, 33], dtype=float)

# Display the array with type
print(arr)
```

Output:

```[11. 22. 33.]
```

Although we supplied a list of integers, but NumPy array `arr` was created with elements of float type only. It is because we explicitly passed the `dtype` parameter with value `float`.

### NumPy Arrays with Different Data Types

If you try to create an array with different data types, such as strings and numbers, NumPy will convert them to the same data type, selecting the one that can represent all the elements, typically strings:

```import numpy as np

# Create an array with mixed data types
arr = np.array(['Sample', True, 24, 10.6])

# Display the array
print(arr)
```

Output:

```['Sample' 'True' '24' '10.6']
```

This array will contain all string values because strings can represent both text and numbers.

## Higher-Dimensional Arrays

NumPy can easily handle multi-dimensional arrays. Let’s see how to create a 3-dimensional array:

```import numpy as np

# Create a 3D array
arr3D =np.array([[[11, 32, 23],
[24, 45, 36]],
[[17, 18, 29],
[11, 12, 32]]
])

# Display the 3D array
print(arr3D)
```

Output:

```[[[11 32 23]
[24 45 36]]

[[17 18 29]
[11 12 32]]]
```

This array is composed of two 2D arrays, each containing two rows and three columns.

## NumPy Array Attributes and Methods

NumPy arrays come with attributes and methods that allow us to inspect and manipulate them. Although we’ll explore these in detail in our next session, let’s look at a couple of attributes:

• `ndim`: This tells you the number of dimensions of the array.
• `shape`: This gives you the size of the array in each dimension.

Let’s check the attributes of our 2D array:

```import numpy as np

# Create a 2D array from a list of lists
arr2D = np.array([[12, 34, 67],
[42, 10,-33],
[11, 12, 22],
[23, 24, 25]])

# Display the 2D array
print(arr2D)

print(arr2D.ndim)  # Output: 2
print(arr2D.shape) # Output: (4, 3)
```

Output:

```[[ 12  34  67]
[ 42  10 -33]
[ 11  12  22]
[ 23  24  25]]
2
(4, 3)
```

## Summary

In this introduction of NumPy Arrays, we’ve learned how to create NumPy arrays of various dimensions and set their data types. We’ve also glimpsed the power of array attributes, we will cover them more extensively in our next artcile.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top