How to Store Multiple Data Types in a Single NumPy Array with Preserved Original Data Types?

DDD
Release: 2024-10-21 17:56:45
Original
655 people have browsed it

How to Store Multiple Data Types in a Single NumPy Array with Preserved Original Data Types?

Storing Multiple Data Types in a Single NumPy Array

You are faced with the challenge of combining two arrays, one containing strings and the other containing integers, into a single array. While your current approach of using np.concatenate results in the entire array being converted to a string dtype, you seek a more efficient solution.

Record Arrays:

One effective approach is to leverage record arrays. This allows you to create "columns" that preserve their original data types. Record arrays are constructed using the numpy.rec.fromarrays function and take arrays representing each column along with their corresponding field names.

<code class="python">import numpy as np

a = np.array(['a', 'b', 'c', 'd', 'e'])
b = np.arange(5)

records = np.rec.fromarrays((a, b), names=('keys', 'data'))

print(records)
# rec.array([('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4)], 
#      dtype=[('keys', '|S1'), ('data', '<i8')])</code>
Copy after login

Structured Arrays:

Another option is to use structured arrays, which are declared with a custom data type. While they lack the attribute access provided by record arrays, they offer a more efficient representation.

<code class="python">arr = np.array([('a', 0), ('b', 1)], 
                      dtype=([('keys', '|S1'), ('data', 'i8')]))

print(arr)
# array([('a', 0), ('b', 1)], 
#      dtype=[('keys', '|S1'), ('data', '<i8')])</code>
Copy after login

By employing record or structured arrays depending on your specific requirements, you can effectively store multiple data types in a single NumPy array while maintaining their original dtypes.

The above is the detailed content of How to Store Multiple Data Types in a Single NumPy Array with Preserved Original Data Types?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!