w3resource

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.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to save a structured array with multiple data types to a text file using np.savetxt with a custom format string.
  • Create a function that converts a record array into a formatted string with specified precision for floats and proper spacing for strings.
  • Implement a solution that writes a matrix with mixed types to a CSV file and then reads it back to verify data integrity.
  • Test the file output by comparing the written text file with expected formatting rules for mixed data types.

Go to:


PREV : Count instances of values based on conditions.
NEXT : Merge three arrays of the same shape.


Python-Numpy Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.