numpy.loadtxt() in Python
The Python numpy.loadtxt() function loads data from text file. In this text file each row must have same number of values.
Basic Syntax
Following is the basic syntax for numpy.loadtxt() function in Python:
numpy.loadtxt(name, dtype=’float’, comments=’#’, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding=’bytes’)
And the parameters are:
Parameter | Description |
---|---|
name | This can be file, filename or generator to read. If generators are there then they should return byte string for Python 3k. If Extension of the file is .gz or .bz2 then the file is first decompressed. |
dtype | [default = float, OPTIONAL]. This is the data type of resulting array. |
comments | [default = ‘#’, OPTIONAL]. Charactors to indicate start of comment. |
delimeter | [default = None, OPTIONAL]. The string used to separate values. |
converters | [default = None, OPTIONAL]. A dictionary mapping column number to a function that will convert column string into desired value. |
skiprows | [default = 0, OPTIONAL]. Skip the first skiprow lines |
usecols | [default = None, OPTIONAL]. Columns to read starts with 0. if usecols= (1,5,7) then it will extract 2nd, 6th and 8th column. |
Return Value
This function loads data from a text file.
Examples
Following are the examples:
Example 1
# Python program for illustration of loadtxt() function import numpy as np # StringIO which behaves like file object from io import StringIO demostring = StringIO("10 20 30 \n40 50 60") result = np.loadtxt(demostring) print(result)
The output for the above program is as given below:
[[ 10. 20. 30.]
[ 40. 50. 60.]]
[ 40. 50. 60.]]
Example 2
# Python program for illustration of loadtxt() function import numpy as np # StringIO which behaves like file object from io import StringIO demostring = StringIO("10, 20, 30, 40\n50, 60, 70, 80") v, x, y, z = np.loadtxt(demostring, delimiter =', ', usecols =(0, 1, 2, 3), unpack = True) print("v is: ", v) print("x is: ", x) print("y is: ", y) print("z is: ", z)
The output for the above program is as given below:
z is: [ 10. 50.]
x is: [ 20. 60.]
y is: [ 30. 70.]
z is: [ 40. 80.]
x is: [ 20. 60.]
y is: [ 30. 70.]
z is: [ 40. 80.]
LATEST POSTS
-
numpy.append() in Python
-
numpy.reshape() in Python
-
Binary Search in C++
-
numpy.arange() in Python
-
Substring in C++
-
numpy.matrix() in Python
-
Python string strip() method
-
Binary Search in Java
-
PHP explode() function
-
Java Stack Class Tutorial with Examples
-
numpy.mean() in Python
-
C++ strncmp() function with example