What's the fastest way to generate delimited string from 1d NumPy array?

Learn about the fastest way to generate delimited string from 1d NumPy array in Python?
By Pranit Sharma Last updated : December 25, 2023

The separator character which is generally used in a data file for separating the data is called a delimiter. There are some more popular delimiters. E.g.: tab(\t), colon (:), semi-colon (;) etc.

Problem statement

Suppose that we are given a 1D NumPy array of float values and we need to convert these floats into delimited strings.

Generating delimited string from 1d NumPy array

To generate delimited strings from the array, we first need to generate an array with strings and then we will the strings using the str.join() function.

Consider the below code statement for this,

res = ",".join(arr_str)

Let us understand with the help of an example,

Python code to generate delimited string from 1d NumPy array

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.random.random(10)

# Display Original array
print("Original array:\n",arr,"\n")

# Creating array of strings
arr_str = np.char.mod('%f', arr)

# Display array of strings
print("Array of strings:\n",arr_str,"\n")

# Joining strings
res = ",".join(arr_str)

# Display result
print("Result:\n",res)

Output

Example: What's the fastest way to generate delimited string from 1d NumPy array?

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.