Home »
Python »
Python Programs
Load text file containing both float and string using numpy.genfromtxt()
In this tutorial, we will learn how to load text file containing both float and string using numpy.genfromtxt() in Python?
By Pranit Sharma Last updated : April 11, 2023
Overview
Suppose that we are given a text file that contains data in float and string type and we need to load this data using numpy where we need to fetch both float and string values and want each row to be treated as a separate 1d array.
Load text file containing both float and string
To load text file containing both float and string, we use numpy.genfromtxt(), by specifying the dtype=None, which will tell genfromtxt() to intelligently guess the dtype of each column. Most conveniently, it relieves us of the burden of specifying the number of bytes required for the string column.
Let us understand with the help of an example,
Python code to load text file containing both float and string using numpy.genfromtxt()
# Import numpy
import numpy as np
# Loading txt file
res = np.genfromtxt('test.txt',
delimiter=',',
dtype=None,
names=('sepal length', 'sepal width', 'petal length', 'petal width', 'label')
)
# Display file content
print("Result:\n",res)
Output
Python NumPy Programs »