【问题标题】:applying a mask on a nested numpy array - numpy - python在嵌套的 numpy 数组上应用掩码 - numpy - python
【发布时间】:2017-01-26 23:25:16
【问题描述】:

有点尴尬,因为关于 Numpy 的大量文档,但我被困在做这个简单的任务,即在嵌套的 numpy 表示中获取掩码为真的所有记录(相当于 @987654322 中的 dataframe.loc[cond] @):

import numpy as np
a1 = np.array([1,2,3])
a2 = np.array(['a','b','c'])
a3 = np.array(['luca','paolo','francesco'])
a4 = np.array([True, False,False], dtype='bool')

combination = np.array([a1,a2,a3,a4])
print(combination)

# slice for a4 == True 
combination[combination[3] == 'True']

但结果不是我想要的。

实际上来自combination

[['1' '2' '3']
 ['a' 'b' 'c']
 ['luca' 'paolo' 'francesco']
 ['True' 'False' 'False']]

它产生 combination[combination[3] == 'True']:

array([['1', '2', '3']], 
      dtype='<U11')

当我真正想要时:

[['1']
 ['a' ]
 ['luca']
 ['True' ]]

关于我做错了什么有什么想法吗?

P.S.:不,我不能在 pandas 中执行此操作,因为 pandas 在将其转换为 pandas.Dataframe 时我的 RAM 会爆炸

【问题讨论】:

    标签: python arrays numpy indexing slice


    【解决方案1】:

    我相信您只是缺少另一个维度的索引:

    combination[combination[3] == 'True']
    

    应该是

    combination[:, combination[3] == 'True']
    

    注意冒号。

    这会产生一个新的 ndarray 索引在所有第一个维度上,并且在第二个维度上只有 0。

    【讨论】:

    • 意识到这一点后感觉要砸键盘了。感谢您的快速回答!
    猜你喜欢
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多