【问题标题】:how to implement logical and on array length?如何实现逻辑和数组长度?
【发布时间】:2016-03-09 14:09:27
【问题描述】:

我需要翻译matlab代码

indexSelect0 = a.index1==0 & a.index2==wRange;

变成了一种快速的python风格。我的尝试是:

idx1=np.array(np.where(a['index2'][:,0]==wIndex2))
idx=np.array(np.where(a['index1'][:,0]==wIndex1))
indexSelect0 = ma.masked_array(idx,mask=[not (i in idx1[0,:]) for i in idx[0,:]])

但由于数组很长(超过 5M 的样本),因此需要一段时间。

问题可以表述为:我有一组由不同观察组成的数据。我有 2 个索引可以让我知道在哪里是什么。但我无法找到组合两个选项来过滤数据的正确方法。

希望清楚。

感谢您的帮助

【问题讨论】:

  • 你的a 是什么?是数据框吗?能否提供样本数据?
  • a 是一个字典。如果 a 是数据框会更容易吗?

标签: python arrays matlab numpy logical-operators


【解决方案1】:

对于备份,我找到了答案。感谢 Anton 指导我使用 DataFrame

import pandas as pd
d = {'index1': a['index1'][:,0].squeeze(), 'index2': a['index2'][:,0].squeeze(), 'data': x}
df= pd.DataFrame(data=d)
y = df[(df.index1==wIndex1) & (df.index2==wIndex2)]

所以我使用 pandas 模块的 DataFrame 和布尔运算符来索引和选择数据(更多信息在这里 http://pandas.pydata.org/pandas-docs/stable/indexing.html)。它运行良好:可读、编码简单且速度更快。

【讨论】:

    【解决方案2】:

    struct 转换为dict 与您的MATLAB 完全等效的是:

    indexSelect0 = (a['index1'] == 0) & (a['index2'] == wRange)
    

    在我用了 5 年的笔记本电脑上,我能够在几秒钟内处理 1000 万个样本:

    n = 10000000
    a = {'index1': np.random.randint(0, 10, n), 'index2': np.random.randint(0, 10, n)}
    wRange = 5
    indexSelect0 = (a['index1'] == 0) & (a['index2'] == wRange)
    

    【讨论】:

      猜你喜欢
      • 2016-09-01
      • 2022-09-25
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多