Saturday, 27 April, 2024
HomeProgrammingPythonConverting a Python Dictionary to a NumPy Array - Multiple Methods

Converting a Python Dictionary to a NumPy Array – Multiple Methods

NumPy is a widely used Python library for numerical computations and scientific applications, particularly known for its capabilities in handling large multi-dimensional arrays and matrices. This article explores various methods to convert a Python dictionary into a NumPy array, with step-by-step examples and detailed explanations.

Method 1: Using the numpy.array() function The numpy.array() function allows us to create a NumPy array from a dictionary. Here’s how it’s done:

import numpy as np

# Create a dictionary
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 22],
        'Score': [85, 92, 78]}

# Convert the dictionary to a NumPy array
array = np.array(list(data.values()))

print("Original Dictionary:")
print(data)

print("NumPy Array:")
print(array)

print("Array Type:", type(array))

Output:

Original Dictionary:
{'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 22], 'Score': [85, 92, 78]}
NumPy Array:
[['Alice' 'Bob' 'Charlie']
 ['25' '30' '22']
 ['85' '92' '78']]
Array Type: <class 'numpy.ndarray'>

Method 2: Using the numpy.asarray() function The numpy.asarray() function is similar to numpy.array() and can be used to convert a dictionary into a NumPy array. Here’s an example:

import numpy as np

data = {'Weight': [68, 75, 61, 82],
        'Height': [165, 180, 160, 175]}

array = np.asarray(list(data.values()))

print("Original Dictionary:")
print(data)

print("NumPy Array:")
print(array)

print("Array Type:", type(array))

Output:

Original Dictionary:
{'Weight': [68, 75, 61, 82], 'Height': [165, 180, 160, 175]}
NumPy Array:
[[ 68  75  61  82]
 [165 180 160 175]]
Array Type: <class 'numpy.ndarray'>

Method 3: Using a Loop You can also convert a dictionary to a NumPy array using a loop. Here’s an example with detailed explanation:

import numpy as np

data = {'Temperature': [25, 30, 22, 28],
        'Humidity': [45, 60, 35, 50]}

# Create an empty NumPy array of the same length as the dictionary values
array = np.zeros((len(data), len(list(data.values())[0])))

# Initialize an index variable
i = 0

# Iterate through the dictionary keys and values
for key, values in data.items():
    array[i] = values
    i += 1

print("Original Dictionary:")
print(data)

print("NumPy Array:")
print(array)

print("Array Type:", type(array))

Output:

Original Dictionary:
{'Temperature': [25, 30, 22, 28], 'Humidity': [45, 60, 35, 50]}
NumPy Array:
[[25. 30. 22. 28.]
 [45. 60. 35. 50.]]
Array Type: <class 'numpy.ndarray'>

Method 4: Using the numpy.fromiter() function The numpy.fromiter() function allows you to convert a dictionary into a NumPy array while specifying the data type. Here’s an example:

import numpy as np

data = {'Population': [1000, 2500, 1500],
        'Area': [50, 70, 60]}

array = np.fromiter(data.values(), dtype=int)

print("Original Dictionary:")
print(data)

print("NumPy Array:")
print(array)

print("Array Type:", type(array))

Output:

Original Dictionary:
{'Population': [1000, 2500, 1500], 'Area': [50, 70, 60]}
NumPy Array:
[1000 2500 1500   50   70   60]
Array Type: <class 'numpy.ndarray'>

Method 5: Using the numpy.column_stack() function If you want to convert a dictionary into a multi-row NumPy array, you can utilize the numpy.column_stack() function. Here’s an example:

import numpy as np

data = {'Weight': [68, 75, 61, 82],
        'Height': [165, 180, 160, 175]}

array = np.column_stack(data[key] for key in data)

print("Original Dictionary:")
print(data)

print("NumPy Array:")
print(array)

print("Array Type:", type(array))

Output:

Original Dictionary:
{'Weight': [68, 75, 61, 82], 'Height': [165, 180, 160, 175]}
NumPy Array:
[[ 68 165]
 [ 75 180]
 [ 61 160]
 [ 82 175]]
Array Type: <class 'numpy.ndarray'>

This article has demonstrated multiple methods to convert a Python dictionary into a NumPy array, offering flexibility and various approaches to suit different use cases. The choice of method may depend on your specific requirements and the structure of your data.

Related articles

Most Popular