Python中如何保存含自定义列名的coef_matrix_simple至文本文件?
Got it, let's sort out how to save your coef_matrix_simple DataFrame along with its column names (col) to a text file. The problem with your original np.savetxt() approach is that it’s built for raw numeric arrays—so it doesn’t automatically preserve column headers or row indices by default.
Simplest Solution: Use Pandas' to_csv()
Pandas' DataFrame has a built-in to_csv() method that handles headers and indices out of the box, which is way more straightforward than numpy's method for this use case. Here's your modified code:
col = ['rss','intercept'] + ['coef_x_%d'%i for i in range(1,16)] ind = ['model_pow_%d'%i for i in range(1,16)] coef_matrix_simple = pd.DataFrame(index=ind, columns=col) for i in range(1,16): coef_matrix_simple.iloc[i-1,0:i+2] = linear_regression(df, power=i, models_to_plot=models_to_plot) pd.options.display.float_format = '{:,.2g}'.format # Save with column headers and row indices (matches your original space delimiter) coef_matrix_simple.to_csv('output.csv', sep=' ', float_format='{:,.2g}'.format)
Key Details:
sep=' ': Keeps the space delimiter you used withnp.savetxt()float_format='{:,.2g}'.format: Ensures the number formatting matches what you set withpd.options.display.float_format- If you don't want to save the row indices, add
index=Falseto theto_csv()call:coef_matrix_simple.to_csv('output.csv', sep=' ', float_format='{:,.2g}'.format, index=False)
Alternative: Using np.savetxt() (If You Must)
If you need to stick with numpy for some reason, you’ll have to manually write the header and combine indices with your data. This is more clunky, but here’s how:
col = ['rss','intercept'] + ['coef_x_%d'%i for i in range(1,16)] ind = ['model_pow_%d'%i for i in range(1,16)] coef_matrix_simple = pd.DataFrame(index=ind, columns=col) for i in range(1,16): coef_matrix_simple.iloc[i-1,0:i+2] = linear_regression(df, power=i, models_to_plot=models_to_plot) pd.options.display.float_format = '{:,.2g}'.format # Manually write header and data with open('output.csv', 'w') as f: # Write column headers as a space-separated line f.write(' '.join(col) + '\n') # Combine row indices with numeric data data_with_indices = np.hstack([np.array(coef_matrix_simple.index).reshape(-1, 1), coef_matrix_simple.values]) # Save the combined data np.savetxt(f, data_with_indices, delimiter=' ', fmt='%s')
This works, but you have to handle formatting for both string indices and numeric values, which is why the pandas method is preferred.
内容的提问来源于stack exchange,提问作者SANDIPAN DAWN

