根据条件过滤python中的列表

时间:2018-03-13 14:49:05

标签: python arrays numpy boolean

我有以下实现,其中CSV文件被转换为一行numpy数组:

results = []
with open(file2) as csvfile:
    reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC) 
# change contents to floats
    for row in reader: # each row is a list
        results.append(row)
        print(numpy.percentile(results, perc, axis = None))
        perc_value = numpy.percentile(results, perc, axis = None)

现在的想法是,基于用户提供的返回特定值的百分位数 - 让我们说100我想删除数组中低于100的所有条目。

so example results is [1, 50, 200, 500, 1000, 2000]
perc_value = 100
end result should be [200, 500, 1000, 2000]

我尝试了多次尝试,但要么我收到布尔值的错误,要么numpy或条件不能应用于列表,任何想法?

我试过以下:

       for i in range (len(results)):
           if results[i] > perc_value: results.pop(i)
       print (results)

错误消息: ValueError:具有多个元素的数组的真值是不明确的。使用a.any()或a.all()

1 个答案:

答案 0 :(得分:0)

有时候人们会认为复杂......保持简单并在过程的早期选择......

Row = string。

# arbitrary taken selector values and char.
key      = 100 
position = 4
splitter = '.'

for row in reader: # row as a string.

    # preprocess input
    string_row = str(row)
    row_data = string_row.split (splitter)

    if int(row_data[position]) == key: # selection is done here

        results.append(row)
        print(numpy.percentile(results, perc, axis = None))
        perc_value = numpy.percentile(results, perc, axis = None)

Row =带变量的列表:

# arbitrary taken selector values and char.
key      = 100 
position = 4
splitter = '.'

for row in reader: # each row is a list

    if int(row[position]) == key: # selection is done here

        results.append(row)
        print(numpy.percentile(results, perc, axis = None))
        perc_value = numpy.percentile(results, perc, axis = None)