Import Text Files Into Numpy Arrays - Python
We have to import data from text files into Numpy arrays in Python. By using the
[Link]() and [Link]() functions, we can efficiently read data
from text files and store it as arrays for further processing.
[Link]( ) - Used to load text file data
[Link]( ) - Used to load data from a text file, with missing values handled
as defined.
Note: [Link]( ) is equivalent function to [Link]( ) when no data is
missing.
Using [Link]()
[Link]() function is one of the most commonly used methods to import data from
a text file into a NumPy array. It can read a variety of text files that have structured data
like numbers or strings, and it can handle delimiter-separated values such as CSV, TSV,
or space-separated files.
Example 1: Importing Text file into Numpy arrays
The following '[Link]' text file is considered in this example.
Output :
import numpy as np [[ 1 2]
[ 3 4]
# Text file data converted to integer data type [ 5 6]
[ 7 8]
d = [Link]("[Link]", dtype=int) [ 9 10]]
print(d)
Explanation: This code uses the [Link]() function to read data from
the text file [Link] and convert the data into a NumPy array with
integer data type (dtype=int). The resulting array is then printed.
Example 2: Importing text file into NumPy array by skipping first row
import numpy as np
# skipping first row converting file data to string
d = [Link]("[Link]", skiprows=1, dtype='str')
print(d)
Output :
[['2' 'Bunty']
['3' 'Tinku']
['4' 'Rina']]
Explanation: This code uses [Link]() to read data from the text file [Link],
skipping the first row and converting the remaining data into a NumPy array of strings
(dtype='str'). The resulting data is then printed.
Use skip_footer=1 to skip last row.
[Link]() is a more flexible function that can handle missing data, non-numeric
data, and more complex file formats. It's generally used when dealing with more complex text
files.
Example 3: Importing only the first column(Names) of text file into numpy arrays
The indexing in NumPy arrays starts from 0. Hence, the Roll column in the text file is the 0th
column, Names column is the 1st column and the Marks are the 2nd column in the text file
'[Link]'.
import numpy as np
# only column1 data is imported into numpy array from text file
d = [Link]("[Link]", usecols=1, skiprows=1, dtype='str')
for each in d:
print(each)
Output :
Ankit
Bunty
Tinku
Rina
Rajesh
Explanation: This code uses [Link]() to read data from the text file [Link],
skipping the first row and importing only the data from column 1 (usecols=1). The data is