w3resource

NumPy: Save as text a matrix which has in each row 2 float and 1 string at the end

NumPy: Array Object Exercise-164 with Solution

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:

Previous: Create two arrays of six elements. Write a NumPy program to count the number of instances of a value occurring in one aray on the condition of another array.
Next: Write a NumPy program to merge three given NumPy arrays of same shape.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-164.php