【问题标题】:Select from a 2D list all rows where a column has a desired value从 2D 列表中选择列具有所需值的所有行
【发布时间】:2020-05-09 20:35:49
【问题描述】:

我有一个 MxN 元素的 2D 列表。我想要所有那些列 j 具有特定值的行。我的想法是:

my_2D_list = np.transpose(np.array(my_2D_list))
temp = my_2D_list[my_2D_list[j] == myvalue]

但 temp 为空。如果我打印 my_2D_list 我可以看到数组被转置,但它就像:

 [['0' '0' '0' ... '0' '0' '0']
  ['0' '0' '1' ... '75' '80' '80'] 
  ['60' '60' '0' ... '10' '108' '108']  ...

列之间没有逗号,所以我猜它不是在新矩阵的列中拆分每一行,而是一种连续体......我该如何解决这个问题?

【问题讨论】:

    标签: python-3.x list numpy multidimensional-array transpose


    【解决方案1】:

    要从矩阵中的列中选择值,您必须这样做:

    list[row_idx, col_idx]
    

    其中索引的第一个参数是行索引,第二个参数是列索引。 You can check the docs in here.

    在您的情况下,这看起来像这样:my_2D_list[:, j]。这是一个完整的示例供您检查:

    j = 2
    n = 1
    
    np.random.seed(42)
    my_2D_list = np.random.randint(0, 3, 100).reshape((10, 10))
    
    print(">>> Whole matrix\n%s" % my_2D_list)
    print("\n>>> Column %d\n%s" % (j, my_2D_list[:,j]))
    print("\n>>> Rows where column %d == %d \n%s" % (j, n, my_2D_list[my_2D_list[:,j] == n]))
    

    输出:

    >>> Whole matrix
    [[2 0 2 2 0 0 2 1 2 2]
     [2 2 0 2 1 0 1 1 1 1]
     [0 0 1 1 0 0 0 2 2 2]
     [1 2 1 1 2 1 2 2 0 2]
     [0 2 2 0 0 2 1 0 1 1]
     [1 0 1 0 1 2 2 0 2 2]
     [1 0 1 1 1 1 1 1 1 0]
     [2 1 1 1 1 1 1 2 2 1]
     [2 0 1 0 0 1 2 0 1 0]
     [0 0 0 2 0 0 0 2 0 0]]
    
    >>> Column 2
    [2 0 1 1 2 1 1 1 1 0]
    
    >>> Rows where column 2 == 1 
    [[0 0 1 1 0 0 0 2 2 2]
     [1 2 1 1 2 1 2 2 0 2]
     [1 0 1 0 1 2 2 0 2 2]
     [1 0 1 1 1 1 1 1 1 0]
     [2 1 1 1 1 1 1 2 2 1]
     [2 0 1 0 0 1 2 0 1 0]]
    

    【讨论】:

    • 我会接受你的回答,因为它正在工作,而且这是我问的,但实际上,我发现由于我的一个专栏有文字,虽然我正在寻找的专栏是int 并且我正在与该索引的 int 进行比较,我必须将其与 str(myvalue) 进行比较。否则我的方法也会奏效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多