search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to
chevron_leftDocumentation
Method argpartition
NumPy Random Generator4 topics
Method choiceMethod dotMethod finfoMethod histogramMethod iinfoMethod maxMethod meanMethod placeMethod rootsMethod seedMethod uniformMethod viewMethod zerosMethod sumObject busdaycalendarMethod is_busdayProperty dtypeMethod uniqueMethod loadtxtMethod vsplitMethod fliplrMethod setdiff1dMethod msortMethod argsortMethod lexsortMethod aroundMethod nanmaxMethod nanminMethod nanargmaxMethod nanargminMethod argmaxMethod argminProperty itemsizeMethod spacingMethod fixMethod ceilMethod diffProperty flatProperty realProperty baseMethod flipMethod deleteMethod amaxMethod aminMethod logical_xorMethod logical_orMethod logical_notMethod logical_andMethod logaddexpMethod logaddexp2Method logspaceMethod not_equalMethod equalMethod greater_equalMethod lessMethod less_equalMethod remainderMethod modMethod emptyMethod greaterMethod isfiniteMethod busday_countMethod repeatMethod varMethod random_sampleMethod randomMethod signMethod stdMethod absoluteMethod absMethod sortMethod randintMethod isrealMethod linspaceMethod gradientMethod allMethod sampleProperty TProperty imagMethod covMethod insertMethod logMethod log1pMethod exp2Method expm1Method expMethod arccosMethod cosMethod arcsinMethod sinMethod tanMethod fromiterMethod trim_zerosMethod diagflatMethod savetxtMethod count_nonzeroProperty sizeProperty shapeMethod reshapeMethod resizeMethod triuMethod trilMethod eyeMethod arangeMethod fill_diagonalMethod tileMethod saveMethod transposeMethod swapaxesMethod meshgridProperty mgridMethod rot90Method log2Method radiansMethod deg2radMethod rad2degMethod degreesMethod log10Method appendMethod cumprodProperty nbytesMethod tostringProperty dataMethod modfMethod fmodMethod tolistMethod datetime_as_stringMethod datetime_dataMethod array_splitMethod itemsetMethod floorMethod put_along_axisMethod cumsumMethod bincountMethod putMethod putmaskMethod takeMethod hypotMethod sqrtMethod squareMethod floor_divideMethod triMethod signbitMethod flattenMethod ravelMethod rollMethod isrealobjMethod diagMethod diagonalMethod quantileMethod onesMethod iscomplexobjMethod iscomplexMethod isscalarMethod divmodMethod isnatMethod percentileMethod isnanMethod divideMethod addMethod reciprocalMethod positiveMethod subtractMethod medianMethod isneginfMethod isposinfMethod float_powerMethod powerMethod negativeMethod maximumMethod averageMethod isinfMethod multiplyMethod busday_offsetMethod identityMethod interpMethod squeezeMethod get_printoptionsMethod savez_compressedMethod savezMethod loadMethod asfarrayMethod clipMethod arrayMethod array_equivMethod array_equalMethod frombufferMethod set_string_functionMethod matmulMethod genfromtxtMethod fromfunctionMethod asscalarMethod searchsortedMethod full_likeMethod fullMethod shares_memoryMethod ptpMethod digitizeMethod argwhereMethod geomspaceMethod zeros_likeMethod fabsMethod flatnonzeroMethod vstackMethod dstackMethod fromstringMethod tobytesMethod expand_dimsMethod ranfMethod arctanMethod itemMethod extractMethod compressMethod chooseMethod asarrayMethod asmatrixMethod allcloseMethod iscloseMethod anyMethod corrcoefMethod truncMethod prodMethod crossMethod true_divideMethod hsplitMethod splitMethod rintMethod ediff1dMethod lcmMethod gcdMethod cbrtMethod flipudProperty ndimMethod array2stringMethod set_printoptionsMethod whereMethod hstack
Char32 topics
check_circle
Mark as learned
thumb_up
2
thumb_down
0
chat_bubble_outline
0
Comment
auto_stories Bi-column layout
settings

NumPy | loadtxt method

schedule Aug 12, 2023
Last updated
local_offer
PythonNumPy
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

NumPy's loadtxt(~) method reads a text file, and parses its content into a NumPy array.

Parameters

1. fnamelink | string

The name of the file. If the file is not in the same directory as the script, make sure to include the path to the file as well.

2. dtypelink | string or type | optional

The desired data-type of the constructed array. By default, dtype=float.

3. commentslink | string or list of strings | optional

If your input file contains comments, then you can specify what identifies a comment. By default, comments="#", that is, characters after the # in the same line will be treated as a comment. You can set None if your text file does not include any comment.

4. delimiterlink | string | optional

The string used to separate your data. By default, the delimiter is a whitespace.

5. converterslink | dict<int,function> | optional

You can apply a mapping to transform your column values. The key is the integer index of the column, and the value is the desired mapping. Check examples below for clarification. By default, dict=None.

6. skiprowslink | int | optional

The number of rows in the beginning to skip. Note that this includes comments. By default, skiprows=0.

7. usecolslink | int or sequence | optional

The integer indices of the columns you want to read. By default, usecols=None, that is, all columns are read.

8. unpacklink | boolean | optional

Instead of having one giant Numpy array, you could retrieve column arrays individually by setting unpack=True. For instance, col_one, col_two = np.loadtxt(~, unpack=True). By default, unpack=False.

9. ndminlink | int | optional

The minimum number of dimensions you want. The allowed values are 0, 1 and 2.

10. encoding | string | optional

The encoding to use when reading the file (e.g. "latin-1", "iso-8859-1"). By default, encoding="bytes".

11. max_rowslink | int | optional

The maximum number of rows to read. By default, all lines are read.

Return value

A NumPy array with the imported data.

Examples

Basic usage

Suppose we have the following text-file called sample.txt:

1 2 3 4
5 6 7 8

To import this file:

a = np.loadtxt("sample.txt")
a
array([[1., 2., 3., 4.],
[5., 6., 7., 8.]])

Note that this Python script resides in the same directory as sample.txt.

Also, notice how the default data type chosen by Numpy is float64, regardless of whether or not the numbers in the text file are all integers:

print(a.dtype)
float64

Specifying the desired data type

Instead of using the default float64, we can specify a type using dtype:

a = np.loadtxt("sample.txt", dtype=int)
a
array([[1, 2, 3, 4],
[5, 6, 7, 8]])

Handling comments

Suppose our sample.txt file is as follows:

1 2 3 4 # I'm the first row!
5 6 7 8 // I'm the second row!

To strip out comments in the text-file, specify comments:

a = np.loadtxt("sample.txt", comments=["#", "//"])
a
array([[1., 2., 3., 4.],
[5., 6., 7., 8.]])

Specifying a custom delimiter

Suppose our sample.txt file is as follows:

1,2
3,4

To use a comma as the delimiter:

a = np.loadtxt("sample.txt", delimiter=",")
a
1,2
3,4

Specifying converters

Suppose our sample.txt file is as follows:

1 2
3 4

Just as an arbitrary example, suppose we wanted to add 10 to all values of the 1st column, and make all the values of the 2nd column be 20:

a = np.loadtxt("sample.txt", converters={0: lambda x: int(x) + 10, 1: lambda x: 20})
a
array([[11., 20.],
[13., 20.]])

Skipping rows

Suppose our sample.txt file is as follows:

1 2 3
4 5 6
7 8 9

To skip the first row:

a = np.loadtxt("sample.txt", skiprows=1)
a
array([[4., 5., 6.],
[7., 8., 9.]])

Reading only certain columns

Suppose our sample.txt file is as follows:

1 2 3
4 5 6

To read only the 1st and 3rd columns (i.e. column index 0 and 2):

a = np.loadtxt("sample.txt", usecols=[0,2])
a
array([[1., 3.],
[4., 6.]])

Unpacking columns

Suppose our sample.txt file is as follows:

1 2
3 4

To retrieve the data per column instead of a single NumPy array:

col_one, col_two = np.loadtxt("sample.txt", unpack=True)
print("col_one:", col_one)
print("col_two:", col_two)
col_one: [1. 2.]
col_two: [3. 4.]

Specifying the desired dimension

Suppose our sample.txt only had one row:

1 2 3 4

By default, loadtxt(~) will generate an one-dimensional array:

a = np.loadtxt("sample.txt")
a
array([1., 2., 3., 4.])

We can specify that we want our array to be two-dimensional by:

a = np.loadtxt("sample.txt", ndmin=2)
a
array([[1., 2., 3., 4.]])

Specifying a maximum number of rows to read

Suppose our sample.txt file is as follows:

1 2
3 4
5 6

To read only the first two rows:

a = np.loadtxt("sample.txt", max_rows=2)
a
robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...