从NumPy数组中删除变量

3
我有一段代码可以创建这个图形,但我不知道如何删除“通道1” - 红线的第一个数据和“通道3” - 蓝线的最后一个数据,即那些垂直线。这两个通道中都有266336个记录,你能帮忙吗? 红色垂直线是第一条记录,蓝色垂直线是最后一条记录。
import iodata as io
import matplotlib.pyplot as plt
import numpy as np
import time

testInstance = io.InputConverter()
start = time.time()
conversionError = io.ConversionError()
#f = testInstance.convert(r"S:\Python\", 1", conversionError)
f = testInstance.convert(r"/Users/Hugo/20160401", "201604010000", 
conversionError)
end = time.time()
print("time elapsed " + str(end - start))

if(conversionError.conversionSucces):
    print("Conversion succesful")
if(conversionError.conversionSucces == False):
    print("Conversion failed: " + conversionError.conversionErrorLog)
print "Done!"

# Create a new subplot for two canals 1 & 3
a = np.amin(f.f)
filename = 'C:/Users/Hugo/20160401/201604010000.dat'
d = open(filename,'rb')
t = u"\u00b0"
headersize = 64
header = d.read(headersize)
ax1 = plt.subplot(211)
ax1.set_title(header[:16] + ', ' +                          # station name
     'Canals: '+header[32:33]+' and '+header[34:35]+ ', '   # canals
     +'Temp'+header[38:43]+t+'C'                            # temperature
    +', '+'Time:'+header[26:32]+', '+'Date'+' '+header[16:26])      # date

plt.ylabel('Pico Tesle [pT]')
plt.xlabel('Time [ms]')
plt.plot(f.f[0,], label='Canal 1', color='r', linewidth=0.75, linestyle="-")
plt.plot(f.f[1,], label='Canal 3', color='b', linewidth=0.75, linestyle="-")
plt.legend(loc='upper right', frameon=False)
plt.grid()
# Create a new subplot for FFT
plt.subplot(212)
plt.title('Fast Fourier Transform')
plt.ylabel('Power [a.u.]')
plt.xlabel('Frequency Hz')
FFTdata = np.sqrt(f.f[0,]*f.f[0,]+f.f[1,]*f.f[1,])**1
samples = FFTdata.size
duration = 300 # in seconds
Fs = float(samples)/duration # sampling frequency (sample/sec)
delta_t = 1.0/Fs
t = np.arange(0, samples, 1)*delta_t
FFTdata_freq = np.abs(np.fft.rfft(FFTdata))**2
freq = np.fft.rfftfreq(samples, d=delta_t)

# Printing data
plt.semilogy(freq, FFTdata_freq)
plt.grid()
#plt.savefig('S:/Hugo/'+"201604010000"+'.png', bbox_inches = 
'tight')
plt.show()
f.f的内容:
>>> print f.f[0,]
[ -59.57011259 -74.20675537 -90.53224156 ..., -1676.9703173 -1676.9703173 -1676.9703173 ]

>>> print f.f[1,] 
[ 1.48413511e+00 4.96417605e+00 8.39303992e+00 ..., -1.67697032e+03 -1.67697032e+03 -1.67697032e+03] 

iodata代码:

import struct
import numpy as np

class ConversionError:
    def __init__(self):
        self.conversionSucces = True
        self.conversionErrorLog = "Correct"

    def reportFailure(self, errorlog):
        self.conversionSucces = False
        self.conversionErrorLog = errorlog

class DataStruct:
    def __init__(self,f,initTime,headerString):
        self.f = f
        self.initTime = initTime
        self.headerString = headerString

class InputConverter:
    def __init__(self):
        self.midAdc = 65536/2
        self.convFactor = 19.54

    def convert(self,filePath,fileName,conversionLog):
        try:
            d_file = open(filePath + "/" + fileName + ".dat", mode='rb')
         except IOError as e:
            conversionLog.reportFailure(e.strerror)

        file = d_file.read()
        datalen = len(file)
        headerString = file[:43]
        initime, = struct.unpack('>H', file[48:50])
        expectedMatrixWidth = (datalen - 72)/4
        outputMatrix = np.zeros((2, expectedMatrixWidth))
        index = 0;
        print "Processing..."
        for i in range(64, datalen-8, 4):
            e1, e2 = struct.unpack('>HH',file[i:i+4])
            outputMatrix[0, index] = (e1 - self.midAdc)/self.convFactor
            outputMatrix[1, index] = (e2 - self.midAdc)/self.convFactor
            index += 1


        return DataStruct(outputMatrix,initime,headerString)

2
❶ 请不要将第三方库重命名为标准库中的模块之一,我花了一些时间才明白为什么在整个互联网上都找不到 io.InputConverter。❷ 鉴于 iodata 模块没有文档(除了可能是 doc 字符串),除非您详细解释一下 f 是什么对象,否则很难提供帮助。您收到的答案似乎是合理的,如果答案对您不好,那是因为 f 不是 ndarray(或者您没有完全理解答案,谁知道呢...)- 请编辑您的问题以解释您对 iodata 的使用。 - gboffi
我把所有东西都加起来了,很抱歉。 - Hiddenguy
如果你表现出改进的承诺,并且你的编辑显然是朝着正确方向迈出的一步,那么你就不需要道歉。 - gboffi
2个回答

1
你可以尝试使用数组切片:
plt.plot(f.f[0,][1:], label='Canal 1', color='r', linewidth=0.75, linestyle="-")
plt.plot(f.f[1,][:-1], label='Canal 3', color='b', linewidth=0.75, linestyle="-")

编辑:

由于数据的性质,像@Dascienz在评论中建议的那样,切掉不止第一个/最后一个数据点是合适的。可以使用以下方法,从两个系列中切掉前50个和后50个数据点:

plt.plot(f.f[0,][50:-50], label='Canal 1', color='r', linewidth=0.75, linestyle="-")
plt.plot(f.f[1,][50:-50], label='Canal 3', color='b', linewidth=0.75, linestyle="-")

运河1 - 红线 - Hiddenguy
如果您在代码中添加行print f.f[0,],控制台的相应输出是什么?我期望它是类似于array([val1, val2, val3, ...])的东西。我对前几个val感兴趣... - scrpy
如果您想使用切片数据进行FFT,请将切片存储在新变量中,例如 f0 = f.f[0,][50:-50]f1 = f.f[1,][50:-50]。然后FFT行变为 FFTdata = np.sqrt(f0*f0 + f1*f1)**1 - scrpy
@landogardner 我考虑了一下并且实现了它,但是出现了一个错误。代码部分:fft1 = (f.f[0,][53:][:-14]) fft2 = (f.f[1,][:-14]) FFTdata = np.sqrt(fft1*fft1+fft2*fft2)**1Traceback (most recent call last): File "C:/Users/iotest.py", line 47, in <module> FFTdata = np.sqrt(fft1fft1+fft2fft2)**1 ValueError: 形状不匹配:(266283,) 和 (266336,) 的操作数无法广播在一起。 - Hiddenguy
看起来你在 fft2 = (f.f[1,][53:-14]) 中忘记了 53。因此,fft1fft2 的长度不一样,所以才会出现错误。 - scrpy
显示剩余10条评论

0

冗长的解释为什么我的第一个答案似乎没有产生影响...


从通道1中删除第一个数据点和从通道3中删除最后一个数据点将无法摆脱异常值。 许多 数据点都对其做出了贡献。

查看f.f [0,] (红色的通道1)和f.f [1,] (蓝色的通道3)的最后三个数据点:它们都是相同的值:-1676.97003 ...。这解释了图形右侧的紫色(即红色和蓝色)尖峰。

此外,请查看f.f [0,] (红色的通道1)的前三个值:它们大致为-60 -75 -90 。显然,仅摆脱第一个数据点将无法消除图形左侧的异常值,其中该值一直上升到超过500 ,下降到小于-500 。这些值必须出现在大于2 但仍远远小于50000 的索引处,这就是为什么它看起来像它们发生在0 处的原因。

简而言之,为了消除异常值,在绘制图表之前需要更仔细地清理数据,而不仅仅是切掉前面和/或后面的值(这就是我最初的答案所做的,我认为是正确的)。

非常感谢您的帮助。您的答案对我有所帮助,但同时也让我对代码的某一部分感到有些困惑,我会在我的问题中添加这部分内容。也许您能够帮助我解决问题。我的意思是如何将这些更改应用于fft图(顺便说一句,它还没有完成,但我认为在切片不必要的数据后应该会发生变化)。 - Hiddenguy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接