【问题标题】:How can I slice a numpy array by the value of the ith field?如何根据第 i 个字段的值对 numpy 数组进行切片?
【发布时间】:2012-08-30 17:28:32
【问题描述】:

我有一个 4 列和很多行的 2D numpy 数组(>10000,这个数字不固定)。

我需要根据其中一列的值创建 n 个子数组;我发现的最接近的问题是How slice Numpy array by column value;尽管如此,我不知道该字段中的确切值(它们是浮点数,并且在我需要的每个文件中都会更改),但我知道它们不超过 20。

我想我可以逐行读取,记录不同的值,然后进行拆分,但我认为有一种更有效的方法来做到这一点。

谢谢。

【问题讨论】:

    标签: arrays numpy split pandas


    【解决方案1】:

    您可以方便地使用多维切片:

    import numpy as np
    
    # just creating a random 2d array.
    a = (np.random.random((10, 5)) * 100).astype(int)
    print a
    print
    
    # select by the values of the 3rd column, selecting out more than 50.
    b = a[a[:, 2] > 50]
    
    # showing the rows for which the 3rd column value is > 50.
    print b
    

    另一个例子,更接近你在评论中的要求(?):

    import numpy as np
    
    # just creating a random 2d array.
    a = np.random.random((10000, 5)) * 100
    print a
    print
    
    # select by the values of the 3rd column, selecting out more than 50.
    b = a[a[:, 2] > 50.0]
    b = b[b[:, 2] <= 50.2]
    
    # showing the rows for which the 3rd column value is > 50.
    print b
    

    这会选择第三列值为 (50, 50.2] 的行。

    【讨论】:

    • 好吧,但是值非常接近,我尝试使用 pandas,但在途中迷路了。
    • @user1621048 我不知道真正发生了什么变化,但我添加了另一个更接近您的意思的示例?
    【解决方案2】:

    您可以将 pandas 用于该任务,更具体地说,可以使用 DataFrame 的 groupby 方法。下面是一些示例代码:

    import numpy as np
    import pandas as pd
    
    # generate a random 20x5 DataFrame
    x=np.random.randint(0,10,100)
    x.shape=(20,5)
    df=pd.DataFrame(x)
    
    # group by the values in the 1st column
    g=df.groupby(0)
    
    # make a dict with the numbers from the 1st column as keys and
    # the slice of the DataFrame corresponding to each number as
    # values of the dict
    d={k:v for (k,v) in g}
    

    一些示例输出:

    In [74]: d[3]
    Out[74]: 
        0  1  2  3  4
    2   3  2  5  4  3
    5   3  9  4  3  2
    12  3  3  9  6  2
    16  3  2  1  6  5
    17  3  5  3  1  8
    

    【讨论】:

    • 问题是关于 numpy,而不是 pandas。与 numpy 相比,pandas 有速度和内存方面的劣势。
    猜你喜欢
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2015-05-12
    • 1970-01-01
    • 2017-03-19
    相关资源
    最近更新 更多