Change language

numpy.loadtxt () in Python

| |

Note that each line in the text file must have the same number of values.

Syntax: numpy.loadtxt (fname, dtype = ’float’, comments = ’#’, delimiter = None, converters = None, skiprows = 0, usecols = None, unpack = False, ndmin = 0)

Parameters:
fname: File, filename, or generator to read. If the filename extension is .gz or .bz2, the file is first decompressed. Note that generators should return byte strings for Python 3k.
dtype: Data-type of the resulting array; default: float. If this is a structured data-type, the resulting array will be 1-dimensional, and each row will be interpreted as an element of the array.
delimiter: The string used to separate values ... By default, this is any whitespace.
converters: A dictionary mapping column number to a function that will convert that column to a float. Eg, if column 0 is a date string: converters = {0: datestr2num}. Default: None.
skiprows: Skip the first skiprows lines; default: 0.

Returns: ndarray

Code # 1:

# Python program explaining
# loadtxt () function

import numpy as geek

 
# StringIO behaves like a file object

from io import StringIO 

 

c = StringIO ( " 0 1 2 3 4 5 " )

d = geek.loadtxt (c)

 

print (d)

Output:

 [[0. 1. 2.] [3. 4. 5.]] 

Code # 2:

# Python program explaining
# loadtxt () function

import numpy as geek

 
# StringIO behaves like a file object

from io import StringIO 

 

c = StringIO ( "1, 2, 3 4, 5, 6" )

x, y, z = geek.loadtxt (c, delimiter = ’,’ , usecols = ( 0 , 1 , 2 ), 

  unpack = True )

 

print ( "x is:" , x)

print ( "y is:" , y)

print ( " z is: " , z)

Output:

 x is: [1. 4.] y is: [2. 5.] z is: [3. 6.] 

Code # 3:

# Python program explaining
# loadtxt () function

import numpy as geek

 
# StringIO behaves like a file object

from io import StringIO 

 

d = StringIO ( "M 21 72 F 35 58" )

e = geek.loadtxt (d, dtype = { ’names’ : ( ’gender’ , ’ age’ , ’weight’ ),

’formats’ : ( ’ S1’ , ’i4’ , ’ f4’ )})

 

print (e)

Output:

 [(b’M’, 21, 72.) (b’F’, 35, 58.)] 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method