我试图在我的Python数据文件中运行一个列,并且只希望在某列中保留值为5,6,7,8或9的数据行。
var = [5, 6, 7, 8, 9]
import glob
import numpy as np
filname = glob.glob(''+fildir+'*')
for k in filname:
data = np.genfromtxt(k,skip_header=6,usecols=(2,3,4,5,8,9,10,11))
if data[:,1] not in var:
continue
" fildir"只是我所有文件所在的目录。 data [:,1]的值范围为1-15,就像我说的那样,我只想保留值为5-9的行。当我运行此代码时,我得到:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
有用的提示吗?
答案 0 :(得分:0)
您的第一个问题是您正在尝试评估numPy数组的布尔值。
if data[:,1] not in var:
在您的示例中,data[:,1]
是您的文件读取为浮点数的所有第二列值的集合。因此,暂时忽略您的usecols=
,包含
1 2 3 4 5 6 7 8
9 10 11 12 13 14 16
将在您的示例中生成
>> data[:,1]
array([2., 10.])
这不是你想要检查的东西。为什么确实发生了错误更详细的解释here。
如果您要做的只是存储第二列中var
列表中包含值的所有行的列表,我建议采用一种简单的方法。
from glob import glob
import numpy as np
var = [5, 6, 7, 8, 9]
filname = glob('fildir/*')
# get the desired rows from all files in folder
# use int as dtype because float is default
# I'm not an expert on numpy so I'll .tolist() the arrays
data = [np.genfromtxt(k, dtype=int, skip_header=6).tolist() for k in filname]
# flatten the list to have all the rows file agnostic
data = [x for sl in data for x in sl]
# filter the data and return all the desired rows
filtered_data = filter(lambda x: x[1] in var, data)
根据您希望保留行的数据结构,可能有更多numPythonic方法可以执行此操作,但这个方法非常简单。