【问题标题】:Modify the values of an array where a list of the same size contains values of another list修改数组的值,其中相同大小的列表包含另一个列表的值
【发布时间】:2020-05-23 10:44:00
【问题描述】:

我有这两个列表:

List_large = ['a','b','c','d']
List_small = ['a','c']

还有这个数组:

check = np.array([0]*len(List_large))
check
Out : array([0, 0, 0, 0])

我想在具有 List_small 值的 List_large 的位置中的数组“检查”中有 1。因此,我想最终拥有这个数组:

array([1, 0, 1, 0])

请问我该怎么办?

【问题讨论】:

    标签: python arrays list numpy numpy-ndarray


    【解决方案1】:

    您可以使用np.isin 方法。

    result = np.isin(List_large, List_small).astype(int)
    

    如果你的 numpy 版本小于 1.13.0,请使用in1d 方法。

    result = np.in1d(List_large, List_small).astype(int)
    

    由于result = np.in1d(List_large, List_small)方法返回一个numpyarrayboolean值,你需要使用astype方法来获得一个list 个 二进制 值,01

    输出

    array([1, 0, 1, 0])
    

    【讨论】:

      【解决方案2】:

      作为使用ternary operator 的列表理解:

      >>> List_large = ['a','b','c','d']
      >>> List_small = ['a','c']
      >>> np.array([1 if c in List_small else 0 for c in List_large])
      array([1, 0, 1, 0])
      

      【讨论】:

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