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)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)
Remember that np.savetxt saves the array in text format and np.loadtxt loads it back as a numpy array with floats by default.
The np.savetxt function saves the 2D array in a text file with default float formatting. When loaded back with np.loadtxt, it returns the same 2D array with float values.
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')?
import numpy as np arr = np.loadtxt('data.txt') print(arr.shape[0])
Each line in the text file corresponds to one row in the loaded array.
The file has 3 lines, so np.loadtxt loads 3 rows in the array.
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')import numpy as np np.savetxt('mixed.txt', [[1, 2], ['a', 4]], fmt='%s') np.loadtxt('mixed.txt')
Consider what happens when np.loadtxt tries to convert non-numeric strings to floats.
np.loadtxt tries to convert all data to floats by default. The string 'a' cannot be converted, so it raises a ValueError.
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?
Both saving and loading must use the same delimiter to match the data format.
Using delimiter=';' in both np.savetxt and np.loadtxt ensures the data is saved and read correctly with semicolon separators.
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?
Look for the parameter that fills missing data with a default number.
The filling_values parameter in np.loadtxt replaces missing values with a specified number during loading.