替换大量 numpy 数组中的值

时间:2021-03-26 06:49:15

标签: python arrays numpy

大家晚上好,我真的在为我的代码而苦苦挣扎。我从拟合文件中制作了一个一维光谱。我已经为文件中的每个点提取了数值,但存在过度曝光像素值的垂直线。我想用 0 替换 3000 以上的所有值。这是我到目前为止所做的:

import astropy as ap
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from astropy.io import fits
from pathlib import Path
from astropy.nddata import CCDData
from ccdproc import ImageFileCollection
import ccdproc as ccdp
from os import listdir, walk
import astropy.units as u

# this function converts the class astropy.io.fits.hdulist.HDUList to a numpy array as ccd data

fitsfile = fits.open("img/HLXSpectrum.fits")
def spec(fitsfile):
    
    specList = fits.open("img/HLXSpectrum.fits", include_path=True)
    imgList = []
    for img in specList:
        ccd = CCDData(fitsfile[0].data, unit="adu")
        HLX = ccdp.trim_image(ccd, fits_section="[:2050, 480:840]")
        imgList.append(ccd)
        fitsfile.close()
    
    specImg = CCDData(ccd, unit="adu")
    return specImg
specImg = spec(fitsfile)

skyarray1 = specImg[180:220, 50:2045]
spectrum1 = np.array(skyarray1)

skyarray2 = specImg[220:260, 50:2045]
spectrum2 = np.array(skyarray2)

skyarray3 = specImg[140:180, 50:2045]
spectrum3 = np.array(skyarray3)

spectrumA = spectrum2 - spectrum3
spectrum = spectrumA - spectrum1

flux = []
pixel = []

fix = np.where(spectrum > 3000, spectrum, 0)

for i in range(len(fix[1])): # cropped img in x dimension
    flux.append(np.sum(skyarray1[:, i]))
    pixel.append(i)

plt.figure(figsize=(20, 16), dpi=800)
plt.plot(pixel, flux, color="red")
fig1 = plt.gcf()
plt.show()

# fig1.savefig("flux.png", dpi=800)

但无论我做什么,图像都保持不变,即使数组中的值发生变化。为什么?

1 个答案:

答案 0 :(得分:0)

问题归结为您在此处绘制的内容:

fix = np.where(spectrum > 3000, spectrum, 0)

for i in range(len(fix[1])): # cropped img in x dimension
    flux.append(np.sum(skyarray1[:, i]))
    pixel.append(i)

plt.figure(figsize=(20, 16), dpi=800)
plt.plot(pixel, flux, color="red")
fig1 = plt.gcf()
plt.show()

您正在绘制 flux,它从未经修改的 skyarray1 获取值。我想你想像这样用 fix 替换它:

for i in range(len(fix[1])): # cropped img in x dimension
    flux.append(np.sum(fix[:, i]))
    pixel.append(i)