You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何保存含自定义列名的coef_matrix_simple至文本文件?

Save DataFrame with Column Headers to Text File

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 with np.savetxt()
  • float_format='{:,.2g}'.format: Ensures the number formatting matches what you set with pd.options.display.float_format
  • If you don't want to save the row indices, add index=False to the to_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:26:22