代码之家  ›  专栏  ›  技术社区  ›  khelili miliana

在列表中拆分基于数组的列值

  •  1
  • khelili miliana  · 技术社区  · 5 年前

    我是新加入numpy的,我想根据列值拆分数组2D,如果值在另一个列表中, 我在2D的numpy数组上转换了一个pandas dataframe,我有另一个列表,我想把我的numpy数组拆分到另外两个数组上,第一个基于(如果列表中第二列的值),第二个数组包含numpy数组的其余部分,我想得到列表的其余部分(包含numy数组中不存在的所有值)

    numpy_data = np.array([
            [1, 'p1', 2],
            [11, 'p2', 8],
            [1, 'p8', 21],
            [13, 'p10', 2] ])
    
    list_value = ['p1', 'p3', 'p8']
    

    预期产出:

    data_in_list = [
            [1, 'p1', 2],
            [1, 'p8', 21]]
    list_val_in_numpy = ['p1', 'p8'] # intersection of second column with my list
    
    rest_data = [
            [11, 'p2', 8],
            [13, 'p10', 2]] 
    rest_list_value = ['p3']
    

    first_output =  numpy_data[np.isin(numpy_data[:,1], list_value)]    
    

    浏览我的列表并在数组的第二列中查找if值,然后删除这行,在这种情况下,我不需要第一个输出(我在_list中调用data_,b-coz我在它上面做我需要的),这里我需要其他输出

    for val in l :
        row = numpy_data[np.where(numpy_data[:,1]== val)]
        row.size != 0 :
            # My custom code
            # then remove this row from my numpy, I couldn't do it
    

    提前谢谢

    3 回复  |  直到 5 年前
        1
  •  2
  •   Gilad Green Fábio    5 年前

    使用python的反转 ~ np.isin :

    rest = numpy_data[~np.isin(numpy_data[:,1], list_value)]    
    
        2
  •  0
  •   Bharath    5 年前

    有多种方法可以做到这一点。我更喜欢使用向量化的方式来理解列表。但为了清楚起见,这里有一个循环的方法来做同样的事情。

    data_in_list=[]
    list_val_in_numpy = []
    rest_data=[]
    for x in numpy_data:
        for y in x:
            if y in list_value:
                data_in_list.append(x)
                for x in list_value:
                    if x == y:
                        list_val_in_numpy.append(x)
    for x in numpy_data:
        if x in data_in_list:
            pass
        else:
            rest_data.append(x)
    

        3
  •  0
  •   Yossi Levi    5 年前

    我想列表理解可以解决这个问题:

    numpy_data = [
            [1, 'p1', 2],
            [11, 'p2', 8],
            [1, 'p8', 21],
            [13, 'p10', 2],
    
    ]
    
    list_value = ['p1', 'p3', 'p8']
    
    output_list = [[item] for item in numpy_data if item[1] in list_value]
    print(output_list)
    

    [[[1, 'p1', 2]], [[1, 'p8', 21]]]