【问题标题】:Split an array according to it's information根据数组的信息拆分数组
【发布时间】:2016-10-10 07:03:06
【问题描述】:

我正在用 python 做一个项目,其中包含 600 个小行星测量值(直径、周期、轨道半径)。有了这些信息,我想根据直径列制作新数组,生成的数组将是第一个数组的直径间隔。

如果我有这个数组,

diameter           period         orbit radius
 [[  19.17          5.71476129    3.19639121]
 [  19.28          4.81234455    2.85035536]
 [  22.77          5.62890294    3.16429553]
 [   4.8           3.29145453    2.21268592]
 [   7.23          2.61331495    1.89724041]
 [   8.17          2.54935585    1.86615697]
 [ 260.94          6.49151957    3.47983602]
 [ 530.            3.62867648    2.3613482 ]
 [ 952.4           4.60562864    2.76813421]]

我想制作一个直径从 0 到 20 的数组

diameter           period         orbit radius
 [[  19.17          5.71476129    3.19639121]
 [  19.28          4.81234455    2.85035536]
 [   4.8           3.29145453    2.21268592]
 [   7.23          2.61331495    1.89724041]
 [   8.17          2.54935585    1.86615697]]

【问题讨论】:

  • 将您的数据加载到 pandas 数据框中,例如 df,然后是 result=df[df["diameter"]<20]
  • 您的数据似乎是行/列形式。我强烈建议你看看pandas

标签: python arrays python-2.7 numpy


【解决方案1】:

只需使用列表推导来过滤它

filtered = [ ast for ast in arr if ast[0]<=20 ]

【讨论】:

    【解决方案2】:

    您可以使用 numpy 数组的索引属性轻松构建新数组,这将转化为一个衬里:

    filtered_arr = arr[(arr[:,0]<=20)*(arr[:,0]>=0),:]
    

    或开发:

    #we separate the diameters from the rest
    diameter_column= arr[:,0]
    #we create a (1D) bool array that match diameter between 0 and 20
    diameter_filter=(diameter_column<=20) * (diameter_column>=0)
    #we use the boolean array as an index to select the right asteroids
    filtered_arr=arr[diameter_filter,:]
    

    【讨论】:

      【解决方案3】:

      假设您想使用numpy 获得所需的矩阵,您可以使用numpy.where 匹配条件,然后应用可用于索引数组以获得所需值的掩码。

      >>>arr[np.where(arr[:, 0] < 20)]
      
      [[ 19.17         5.71476129   3.19639121]
       [ 19.28         4.81234455   2.85035536]
       [  4.8          3.29145453   2.21268592]
       [  7.23         2.61331495   1.89724041]
       [  8.17         2.54935585   1.86615697]]
      

      这里,np.where(arr[:, 0] &lt; 20) 检查数组的第一列,并返回存在有利匹配的行的索引,稍后将用于对原始数组进行切片。

      【讨论】:

        猜你喜欢
        • 2013-04-07
        • 1970-01-01
        • 1970-01-01
        • 2016-07-30
        • 2019-08-16
        • 1970-01-01
        • 1970-01-01
        • 2011-06-15
        • 1970-01-01
        相关资源
        最近更新 更多