python - 如何将字符串和 float 加载到 numpy 数组中?

标签 python arrays list numpy io

我需要以某种方式在文本和数字中进行 numpy 加载。

我收到此错误:

Traceback (most recent call last):
  File "ip00ktest.py", line 13, in <module>
    File = np.loadtxt(str(z[1]))        #load spectrum file 
  File "/usr/lib64/python2.6/site-packages/numpy/lib/npyio.py", line 805, in loadtxt
    items = [conv(val) for (conv, val) in zip(converters, vals)]
ValueError: invalid literal for float(): EFF

因为我正在加载的文件中有文本。我需要将每个单词及其下面的数据存储在数组索引中。我该怎么做?

编辑:抱歉没有给出示例。这是我的文件的样子。

FF   3500.  GRAVITY 0.00000  SDSC GRID  [+0.0]   VTURB 2.0 KM/S    L/H 1.25                            
  wl(nm)    Inu(ergs/cm**2/s/hz/ster) for 17 mu in 1221 frequency intervals
            1.000   .900  .800  .700  .600  .500  .400  .300  .250  .200  .150  .125  .100  .075  .050  .025  .010
    9.09 0.000E+00     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0
    9.35 0.000E+00     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0
    9.61 0.000E+00     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0
    9.77 0.000E+00     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0
    9.96 0.000E+00     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0

这里显示的数字下面有数千个数字。此外,文件中存在不同的数据集,因此您在顶部看到的标题会重复,后面跟着一组新的数字。

失败的代码:

import sys
import numpy as np
from math import *

print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

z = np.array(sys.argv)          #store all of the file names into array

i = len(sys.argv)           #the length of the filenames array

File = np.loadtxt(str(z[1]))        #load spectrum file 

最佳答案

如果搞乱它的行总是以 EFF 开头,那么您可以很容易地忽略该行:

np.loadtxt(str(z[1]), comments='EFF')

它将把任何以 'EFF' 开头的行视为注释,并将被忽略。

关于python - 如何将字符串和 float 加载到 numpy 数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16613733/

相关文章:

Python 正则表达式 : Matching from end of string (reverse)

java - 多个数组的公共(public)元素但不使用列表

c - 从二维数组中找到最大值,并将最大值之前的所有值相加,然后将最大值之后的所有值相乘

c# - 排序字符串数字

python - 在 Python 中遍历列表列表中的列

python - 在Python中使用seaborn在分布图上显示峰度、偏度等指标

python - 无法将图像添加到 Windows 上的 GUI(tkinter)

python - 如何匹配 json 汤中的确切单词?

iphone - 当Array更改时自动更新UITableView

list - 计算并删除列表中第一个元素的连续出现次数