【问题标题】:How to check a value against each element in a vector/matrix in Python如何在 Python 中检查向量/矩阵中每个元素的值
【发布时间】:2017-06-13 17:45:18
【问题描述】:

这当然很简单,但现在我已经尝试了几个小时来解决这个问题。 我想根据 10x1 矩阵中的所有值检查一个值,如果它大于其中任何一个,则应将其插入到大于的元素之前。

到目前为止,我已经尝试了以下代码的不同变体,但没有运气。 我得到的只是以下内容:

我尝试过的:

col,col1,col2 = np.zeros((10,1)),np.zeros((10,1)),np.zeros((10,1))

for element in col:             
    if (aggdelay>element):                  
        col[n,0] = aggdelay
        col1[n,0] = flight_num
        col2[n,0] = airline_id
        break               

    n +=1
    if (n>10):
        n=0

我得到的输出如下所示:

[[ 157.]
 [   3.]
 [   6.]
 [   6.]
 [   5.]
 [   9.]
 [   0.]
 [   0.]
 [   0.]
 [   0.]]

输入是:

 19790  1256    124.0
19790   1257    157.0
19790   1258    3.0
19790   1264    6.0
19790   1266    6.0
19790   1280    5.0
19790   1282    9.0

预期的输出是:

19790   1258    3.0
19790   1280    5.0
19790   1264    6.0
19790   1266    6.0
19790   1282    9.0
19790   1256    124.0
19790   1257    157.0

我实现了 David 提供的解决方案,但我发现很难用新元素更新“矩阵”。 这是我目前的解决方案,但我怀疑它没有正确更新。

 #!/usr/bin/python
import sys
import collections
import numpy as np
from operator import itemgetter

result =np.zeros((3,1))
col,col1,col2 = []*10,[]*10,[]*10
col11,col12,col23 = [],[],[]
old_flight_num, old_airline_id = None, None

lines = sys.stdin.readlines()
sumDelay1, num = 0, 1
n = 0
for line in lines:

    line, line = line.strip(), line.split("\t")

    if len(line) !=3:
        continue

    airline_id, flight_num, aggdelay = line

    try:
        aggdelay = float(aggdelay)
        flight_num= int(flight_num)
        airline_id = int(airline_id)
    except ValueError:
        continue

    if (old_airline_id is not None) and (old_airline_id != airline_id):

        res2.sort(key=itemgetter(2))

        print('                                                      ')     
        print('Here come the results for airline ID: ', (old_airline_id))
        print('                                                      ')
        for row in res2:
            print(row)      

        col,col1,col2 = []*10,[]*10,[]*10

        n=0

    if (n<10):
        col.append(airline_id),col1.append(flight_num),col2.append(aggdelay)

    else:   
        res = zip(col,col1,col2)
        res.sort(key=itemgetter(2))

        if (aggdelay>min(col2)):
            res.remove(res[0])
            col11.append(airline_id), col12.append(flight_num), col23.append(aggdelay)
            res1 = zip(col11,col12,col23)
            res2=res+res1

            res2.sort(key=itemgetter(2))
    col11,col12,col23 = [],[],[]    
    n += 1

    old_airline_id = airline_id

if (old_airline_id is not None):

    res2.sort(key=itemgetter(2))
    print('                                                      ')     
    print('Here come the results for airline ID: ', (old_airline_id))
    print('                                                      ')
    for row in res2:
        print(row)

我非常感谢您对此提供一些指导。 谢谢!

【问题讨论】:

  • 什么是“矩阵”? (Python 中没有这种数据类型。)
  • 请显示您的代码 :) 您的问题表明您有一些代码,但可能错误地实际上并未包含您的代码。您打算仅在 第一个 实例中插入,还是在val &gt; element所有 实例中插入?
  • 年,我只需要更换操作系统。我希望我的编辑能胜任大卫的工作。如果我需要详细解释任何事情,请告诉我。如您所见,第三列中的每个数字在第一列和第二列中都有一个所属值。它们还应该与存储值放在相同的索引处。我只是认为在三个向量中进行操作会更容易,然后在最后将它们组合起来。
  • @DYZ 矩阵我的意思是一个多维的numpy数组,这样更令人满意吗?
  • 你试过numpy.insert功能吗?

标签: python loops matrix iteration vectorization


【解决方案1】:

这可能会奏效,但我不得不猜测您对输出的期望以及您如何处理输入(假设在 3 列中给出航空公司 ID、航班号、延误)。

import numpy as np
from operator import itemgetter

ids = [19790,19790,19790,19790,19790,19790,19790,19790]
flight_nums = [1256,1257,1258,1264,1266,1280,1282]
agg_delays = [124.0,157.0,3.,6.,6.,5.,9.]
m = zip(agg_delays,flight_nums,ids)  
m.sort(key=itemgetter(0),reverse=True)  # sorts the zipped list by delay, decreasing

matrix = np.array(m, np.float32)  # dumps the sorted list in to your matrix, an ndarray

这为您提供了一个包含 3 列的 ndarray 对象,第一列是您的“延迟”,然后是航班号,然后是航空公司 ID,并按第一列排序。

如果您只对前 N 个感兴趣,那么只需使用上面的构建整个矩阵并对其进行切片:

# return the top 10, or however many:
matrix = matrix[:10]

不使用list.sort方法和切片,可以倒序排列ndarray对象:

m = zip(agg_delays,flight_nums,ids)
matrix = np.array(m, np.float32)
matrix.sort(0)
# return the top 10, or however many:
matrix = matrix[::-1][:10]

【讨论】:

  • 感谢您在我缺乏信息的情况下尝试使用它。在我看来,如果我有关于航空公司 ID、航班编号和延误的恒定信息量,你的回答就可以了。情况是我有更多数据,而提供的数据只是我数据的一个子集。我需要评估包含airline_id、flight_num 和delay 的每一行,并根据延迟的大小将其放入矩阵中,这样我就可以得到对应airline_id 和flight_num 的数据的前10 个延迟。我希望这能进一步澄清一些事情。
  • 使用此方法构建整个矩阵,然后从您感兴趣的前 10 个(或任意多个)项目中取出一个切片。
  • 非常感谢大卫的意见!我会尝试合并它,然后我会回复你。
  • 当我尝试压缩三个变量时,我收到以下错误:“Zip argument #3 must support iteration” 我该如何处理这个错误信息?延迟是一个浮点数。
  • 在我的示例中,我假设您首先将所有数据收集到列表或其他序列对象中。然后你可以压缩它。
猜你喜欢
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多