python - 我应该如何使用 Numpy 的 vstack 方法?

标签 python numpy

首先,这里是代码的相关部分:

stokes_list = np.zeros(shape=(numrows,1024)) # 'numrows' defined earlier
for i in range(numrows):
    epoch_name = y['filename'][i] # 'y' is an array from earlier
    os.system('pdv -t {0} > temp.txt '.format(epoch_name)) # 'pdv' is a command from another piece of software - here I copy the output into a temporary file
    stokes_line = np.genfromtxt('temp.txt', usecols=3, dtype=[('stokesI','float')], skip_header=1)
    stokes_list = np.vstack((stokes_line,stokes_line))

所以,基本上,每次代码循环时,stokes_line 从文件 temp.txt 中提取其中一列(第 4 列),我希望它每次向 stokes_list 添加一行。

例如,如果第一个 stokes_line

1.1 2.2 3.3  

第二个是

4.4 5.5 6.6  

然后 stokes_list 将是

1.1 2.2 3.3  
4.4 5.5 6.6  

并将继续增长......

目前无法正常工作,因为我认为该行:

stokes_list = np.vstack((stokes_line,stokes_line))

不正确。它只堆叠 2 个列表——这是有道理的,因为我只有 2 个参数。我基本上想知道我是如何一次又一次地堆叠的。

如有任何帮助,我们将不胜感激!
如果需要,这里是 temp.txt 文件的格式示例:

File: t091110_065921.SFTC Src: J1903+0925 Nsub: 1 Nch: 1 Npol: 4 Nbin: 1024 RMS: 0.00118753  
0 0 0 0.00148099 -0.00143755 0.000931365 -0.00296775  
0 0 1 0.000647476 -0.000896698 0.000171287 0.00218597  
0 0 2 0.000704697 -0.00052846 -0.000603842 -0.000868739  
0 0 3 0.000773361 -0.00234724 -0.0004112 0.00358033  
0 0 4 0.00101559 -0.000691062 0.000196023 -0.000163109  
0 0 5 -0.000220367 -0.000944024 0.000181002 -0.00268215  
0 0 6 0.000311783 0.00191545 -0.00143816 -0.00213856  

最佳答案

vstack 一次又一次不好,因为它会复制整个数组。

创建一个普通的 Python list.append 到它,然后将它整个传递给 np.vstack 以创建一个新数组一次。

stokes_list = []
for i in xrange(numrows):
    ...
    stokes_line = ...
    stokes_list.append(stokes_line)

big_stokes = np.vstack(stokes_list)

关于python - 我应该如何使用 Numpy 的 vstack 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12299124/

相关文章:

python - 如何解决 Json 错误 : TypeError: a bytes-like object is required, 而不是 'str'

Python:枚举值与命名单元

python - 询问长度为 2 的数组列表是否包含给定长度为 1 的数组时出现 ValueError

python - 计算不同长度向量中元素出现的总数

python - 在安装时检测 Python 传递依赖问题?

python - 您是否必须为部署选择 pickle scaler 和 ML 模型?

Python:如何用ast重载运算符

python - 如何将 CSV 列转换为标准化 np 数组?

python - 在 python 中保存 .dta 文件

python - 使用 Python 和 Numpy 查找两个三次样条之间的最近点