【问题标题】:How to slice up a numpy array with inequalities?如何分割一个不等式的numpy数组?
【发布时间】:2013-03-09 20:25:57
【问题描述】:

我已尽我所能自行找到解决方案,但我只是没有找到任何相关信息。我有一些从 .tbl 文件中提取的 numpy 数组(这是我用 atpy 提取的天文表格式)。每个数组中大约有 25,000 个数字,我使用 matplotlib 将它们绘制为散点图。 y 轴值直接来自数组,x 轴是两个单独数组中值的简单减法。

没关系,但我真正需要做的是提取某个范围内的值(例如,我需要 y 的值在 10 到 13 之间,x 的值在 0 到 1 之间)。当然,要使情节发挥作用,这些值都必须相互匹配。这是我得到的:

import numpy as np
from numpy import ndarray
import matplotlib.pyplot as plt
import matplotlib
import atpy

twomass = atpy.Table()

twomass.read('/Raw_Data/IRSA_downloads/2MASS_GCbox1.tbl')

hmag = list([twomass['h_m']])

jmag = list([twomass['j_m']])

colorjh = list([j-h for j,h in zip(jmag, hmag)])

x = []

y = []

def list_maker():
for c,h in zip(colorjh, hmag):
    if np.all(c) < 1 == True and np.all(c) > 0 == True and np.all(h) < 13 == True and np.all(h) > 10 == True:
        x.append(c)
        y.append(h)       

list_maker()

plt.scatter(x, y, c='g', s=1, alpha=0.05)

plt.xlabel('Color(J-H)', fontsize=15)           #adjust axis labels here
plt.ylabel('Magnitude (H)', fontsize=15)

plt.gca().invert_yaxis()

plt.legend(loc=2)
plt.title('CMD for Galactic Center (2MASS)', fontsize=20)
plt.grid(True)

plt.show()

我也尝试过这种方法来切片数据,但没有运气:

colorjh = colorjh[colorjh<1]

colorjh = colorjh[colorjh>0]

我尝试了很多不同的方法,包括尝试将这些数组转换为列表,以及许多不同的不等式格式。在这个过程中,我可能让自己离答案更远了,但是这段代码至少打印了整个散点图(它无法像我想要的那样切割数据)。其他一些迭代打印的空白图与我正在寻找的数字范围相去甚远。

我是 python 和这个网站的新手,所以请尽可能明确地提供任何提示等。如果它是超级术语,我可能无法很好地利用你的建议。感谢大家。

【问题讨论】:

    标签: python numpy matplotlib astronomy multidimensional-array


    【解决方案1】:

    这两个条件可以同时完成:

    hmag = np.array(hmag)
    jmag = np.array(jmah)
    colorjh = jmag - hmag
    
    idx = ((colorjh > 0) & (colorjh < 1) & (hmag > 10) & (hmag < 13)).nonzero()[0]
    
    plt.scatter(colorjh[idx], hmag[idx], c='g', s=1, alpha=0.05)
    

    .nonzero()[0] 使其成为索引列表,而不是具有 True 和 False 值的“掩码”,如果我们谈论的是非常长的列表,这可能会更有效。

    【讨论】:

      【解决方案2】:

      尝试以下,我认为它与您的fors 和zips 相同,但应该更快。如果有什么不明白的地方,请在 cmets 中提问,我会编辑:

      hmag = np.array(hmag)
      jmag = np.array(jmah)
      
      colorjh = jmag - hmag
      idx_c = (colorjh > 0) & (colorjh < 1) # where condition on c is met
      idx_h = (hmag > 10) & (hmag < 13) # where condition on h is met
      idx = idx_c & idx_h # where both conditions are met
      
      plt.scatter(colorjh[idx], hmag[idx], c='g', s=1, alpha=0.05)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-10
        • 1970-01-01
        • 2021-03-02
        • 2021-03-08
        • 2018-07-20
        • 2020-10-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多