【问题标题】:'numpy.ndarray' object has no attribute 'write''numpy.ndarray' 对象没有属性 'write'
【发布时间】:2026-01-29 01:30:01
【问题描述】:

我正在编写一个 python 代码来计算球状星团 M15(M15 减少)的天文图像的背景。我的代码可以计算背景并使用 plt.imshow() 绘制它。为了保存减去背景的图像,我必须将它从 numpy.nparray 转换为 str。我尝试了很多东西,包括这里使用的 np.array2string。该文件仅保留为数组,无法保存,因为我需要将其保存为 .fits 文件。有什么想法可以把它变成一个 str 吗? 代码:

#sigma clip is the number of standard deviations from centre value that value can be before being rejected
sigma_clip = SigmaClip(sigma=2.)
#used to estimate the background in each of the meshes
bkg_estimator = MedianBackground()
#define path for reading in images
M15red_path = Path('.', 'ObservingData/M15normalised/')
M15red_images = ccdp.ImageFileCollection(M15red_path)
M15reduced = M15red_images.files_filtered(imagetyp='Light Frame', include_path=True)
M15backsub_path = Path('.', 'ObservingData/M15backsub/')
for n in range (0,59):
    bkg = Background2D(CCDData.read(M15reduced[n]).data, box_size=(20,20), 
                   filter_size=(3, 3), 
                   edge_method='pad', 
                   sigma_clip=sigma_clip, 
                   bkg_estimator=bkg_estimator)
    M15subback = CCDData.read(M15reduced[n]).data - bkg.background
    np.array2string(M15subback)
    #M15subback.write(M15backsub_path / 'M15backsub{}.fits'.format(n))

    print(type(M15subback[1]))

【问题讨论】:

  • 看起来M15subback 是一个数组,它没有write 方法。通常它是一个类似文件的对象,它有一个 write 方法,而不是数组、列表或字符串。
  • array2string操作不到位;它返回一个字符串。从array2string 的结果重新创建一个数组是很困难的,如果不是不可能的话。不要用来保存数组!
  • 什么是fits 文件?我看到您在文件名中使用了fits,但这并没有定义保存方法。如果这是astropy 格式,则适当地标记问题,并使用astropy 函数。 numpy 中没有任何内容使用这种格式。

标签: python-3.x numpy


【解决方案1】:

您可以尝试使用 [numpy.save][1](但它会保存一个“.npy”文件)。在你的情况下,

import numpy as np
...
for n in range (0,59):
    ...
    np.save('M15backsub{}.npy'.format(n), M15backsub)

由于您需要存储一个 numpy 数组,这应该可以工作。

【讨论】:

  • 我需要将该文件保存为适合文件以供分析。