NumPy: Save as text a matrix which has in each row 2 float and 1 string at the end
Save a matrix with mixed data types as text.
Write a NumPy program to save as text a matrix which has in each row 2 float and 1 string at the end.
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Creating a matrix (list of lists)
matrix = [
[1, 0, 'aaa'],
[0, 1, 'bbb'],
[0, 1, 'ccc']
]
# Saving the matrix into a text file named 'test' using savetxt function
# Delimiter ' ' (two spaces) separates the values in the output file
# 'string' is the header written at the top of the file
# comments='' ensures no comments are included in the output file
# fmt='%s' specifies the format as string for all elements in the matrix
np.savetxt('test', matrix, delimiter=' ', header='string', comments='', fmt='%s')
Sample Output:
string 1 0 aaa 0 1 bbb 0 1 ccc
Explanation:
matrix = [[1, 0, 'aaa'], [0, 1, 'bbb'], [0, 1, 'ccc']]: This line creates a 2D list (matrix) with the given elements.
np.savetxt('test', matrix, delimiter=' ', header='string', comments='', fmt='%s'): Call the np.savetxt() function with the following parameters:
- 'test': The name of the output file (without an extension).
- matrix: the 2D list to save to the file.
- delimiter: String or character separating columns.
- header: String that will be written at the beginning of the file.
- comments: String that will be prepended to the header and footer strings, to mark them as comments.
- fmt: A single format, a sequence of formats, or a multi-format string, (in this case, '%s', which indicates that the elements should be treated as strings).
The np.savetxt() function saves the matrix to a file named 'test' (with no file extension) using the said specified delimiter, header, comments, and format.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics