对条件语句使用列表

2024-04-25 06:09:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图遍历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”只是我所有文件所在的目录。数据[:,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()

有什么有用的提示吗?你知道吗


Tags: 数据inimportnumpyfordatavar数据文件
1条回答
网友
1楼 · 发布于 2024-04-25 06:09:06

第一个问题是,您正在尝试计算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)

可能有一种更简单的方法来实现这一点,具体取决于您希望保留行的数据结构,但这种方法非常简单。你知道吗

相关问题 更多 >