0
0
NumPydata~20 mins

np.savetxt() and np.loadtxt() for text in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Text File I/O Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of np.savetxt() and np.loadtxt() with default settings

What will be the output of the following code snippet?

import numpy as np
arr = np.array([[1.5, 2.5], [3.5, 4.5]])
np.savetxt('test.txt', arr)
loaded = np.loadtxt('test.txt')
print(loaded)
NumPy
import numpy as np
arr = np.array([[1.5, 2.5], [3.5, 4.5]])
np.savetxt('test.txt', arr)
loaded = np.loadtxt('test.txt')
print(loaded)
A
[[1.5 2.5]
 [3.5 4.5]]
B
[[1 2]
 [3 4]]
C[1.5 2.5 3.5 4.5]
DSyntaxError
Attempts:
2 left
💡 Hint

Remember that np.savetxt saves the array in text format and np.loadtxt loads it back as a numpy array with floats by default.

data_output
intermediate
1:30remaining
Number of rows loaded by np.loadtxt()

Given a text file data.txt containing the following lines:

10 20 30
40 50 60
70 80 90

What is the number of rows in the numpy array returned by np.loadtxt('data.txt')?

NumPy
import numpy as np
arr = np.loadtxt('data.txt')
print(arr.shape[0])
A3
B9
C1
D0
Attempts:
2 left
💡 Hint

Each line in the text file corresponds to one row in the loaded array.

🔧 Debug
advanced
2:00remaining
Error raised by np.loadtxt() with mixed data types

What error will the following code raise?

import numpy as np
np.savetxt('mixed.txt', [[1, 2], ['a', 4]], fmt='%s')
np.loadtxt('mixed.txt')
NumPy
import numpy as np
np.savetxt('mixed.txt', [[1, 2], ['a', 4]], fmt='%s')
np.loadtxt('mixed.txt')
ATypeError
BValueError
COSError
DNo error, returns array
Attempts:
2 left
💡 Hint

Consider what happens when np.loadtxt tries to convert non-numeric strings to floats.

🚀 Application
advanced
2:30remaining
Saving and loading with custom delimiter

You want to save a 2D numpy array with values separated by semicolons and then load it back correctly. Which code snippet will achieve this?

A
np.savetxt('file.csv', arr, delimiter=';')
loaded = np.loadtxt('file.csv')
B
np.savetxt('file.csv', arr)
loaded = np.loadtxt('file.csv', delimiter=';')
C
np.savetxt('file.csv', arr, delimiter=',')
loaded = np.loadtxt('file.csv', delimiter=';')
D
np.savetxt('file.csv', arr, delimiter=';')
loaded = np.loadtxt('file.csv', delimiter=';')
Attempts:
2 left
💡 Hint

Both saving and loading must use the same delimiter to match the data format.

🧠 Conceptual
expert
1:30remaining
Handling missing values with np.loadtxt()

You have a text file with numeric data but some values are missing and represented as empty strings. Which np.loadtxt parameter helps to handle missing values by replacing them with a specified number?

Amissing_values
Busecols
Cfilling_values
Ddefault_value
Attempts:
2 left
💡 Hint

Look for the parameter that fills missing data with a default number.