【问题标题】:slicing the third element of each array from of a list of arrays (python)从数组列表中切片每个数组的第三个元素(python)
【发布时间】:2017-04-16 17:52:41
【问题描述】:

我有一个字典,其键“组”的第一个元素包含一个数组列表。

stump['Groups'][0]

[array(['a', 65000, 0], dtype=object),
 array(['a', 95000, 1], dtype=object),
 array(['b', 78000, 1], dtype=object),
 array(['b', 19000, 1], dtype=object)]

我想对每一行的第三列进行切片并对它们进行一些操作。 所以第三列值将是 [0,1,1,1]。

stump['Groups'][0][:]
#results in the whole list
[array(['a', 65000, 0], dtype=object),
 array(['a', 95000, 1], dtype=object),
 array(['b', 78000, 1], dtype=object),
 array(['b', 19000, 1], dtype=object)]

但是,在 [:] 前面添加另一个索引器/切片器,只会对该列表的一部分进行切片。

无论如何要在没有循环的情况下做到这一点?

谢谢。

【问题讨论】:

    标签: numpy slice


    【解决方案1】:

    列表理解应该可以完成这项工作:

    [row[2] for row in stump['Groups'][0]]
    

    并将列表作为数组使用:

    np.array([...]) 
    

    这个列表的元素

    array(['a', 65000, 0], dtype=object)
    

    是对象 dtype 数组,与相同事物的列表大致相同。他们有不同的价值观。

    如果您将整个列表包装在 np.array(或 np.stack)中,您将获得一个二维对象 dtype 数组

    In [58]: arr=np.array(alist)
    In [59]: arr.shape
    Out[59]: (4, 3)
    In [60]: arr
    Out[60]: 
    array([['a', 65000, 0],
           ['a', 95000, 1],
           ['b', 78000, 1],
           ['b', 19000, 1]], dtype=object)
    

    这可以像任何其他二维数组一样被索引:

    In [61]: arr[:,2]
    Out[61]: array([0, 1, 1, 1], dtype=object)
    

    astype(int) 可以将该对象数组转换为数字数组。由于字符串元素,无法转换完整的 2d。

    【讨论】:

    • 是的,我忘了我可以把列表变成数组,这样我就可以像任何二维数组一样索引。谢谢=)
    【解决方案2】:

    列表理解 => 返回列表对象

    column_list = [row[2] for row in stump['Groups'][0]]
    

    地图函数 => 返回地图对象

    column_map = map(lambda row: row[2], stump['Groups'][0])
    

    itertools.imap 函数 => 返回迭代器

    column_iterator = itertools.imap(lambda row: row[2], stump['Groups'][0])
    

    numpy 数组切片 -> 返回 numpy.array。 要求 stump['Groups'][0] 为 numpy.array 类型

    columns_array = stump['Groups'][0][:,2]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多