使用numpy.savetxt保存含288浮点数+1字符串的混合矩阵报错
Got it, let's break down why your np.savetxt call is throwing that TypeError and fix it up. The core issue is how you're defining the format string and how numpy handles mixed-type arrays with this function.
What's Causing the Error?
Your current format string '%3f'*288 + '%s' creates a single unbroken string like %3f%3f%3f...%s—no separators between the float formatters. When numpy tries to map each element in your row to this long string, it gets confused about how to match the mixed float/string values to the consecutive format specifiers, leading to the type mismatch error you're seeing.
Fix 1: Use a Format List (Simplest Solution)
Instead of cramming all format specifiers into one string, pass a list where each element corresponds to the format of a column in your matrix. This makes the mapping explicit and avoids parsing issues:
import numpy as np # Create a format list: 288 float formats, plus one string format fmt_spec = ['%3f'] * 288 + ['%s'] # Save the matrix correctly np.savetxt('your_file.txt', matrix, delimiter=' ', header='your_header_string', comments='', fmt=fmt_spec)
Fix 2: Use a Structured Array (For Better Type Control)
If your matrix is stored as an object-type array (common for mixed data types), converting it to a structured array helps numpy handle the types more reliably:
import numpy as np # Define a dtype with 288 float fields and one string field (adjust 'U30' if your strings are longer) dtype_def = [('float_col_{}'.format(i), float) for i in range(288)] + [('string_col', 'U30')] # Convert your matrix to a structured array structured_arr = np.array([tuple(row) for row in matrix], dtype=dtype_def) # Save with a properly spaced format string np.savetxt('your_file.txt', structured_arr, delimiter=' ', header='your_header_string', comments='', fmt='%3f ' * 288 + '%s')
Quick Pre-Save Checks
- Double-check that your
matrixis a 2D array where every row has exactly 289 elements (288 floats + 1 string)—mismatched row lengths will also trigger errors. - If your strings are longer than expected, tweak the string format spec (e.g., use
%20sinstead of%sto reserve space for longer values).
内容的提问来源于stack exchange,提问作者francesco

