【问题标题】:How to extract random rows from a numpy array within unique values of one column如何从一列的唯一值内的numpy数组中提取随机行
【发布时间】:2021-06-02 09:09:31
【问题描述】:

我有一个 numpy 数组,想从中提取一些随机行。 This solution 做到了,但我的情况有点详细。我想根据数组的最后一列找到一些随机行。此列有一些唯一值,我想在每个唯一组中提取随机数。这是我的数组:

import numpy as np
my_array=np.array([['1.66', '1.67', 'group_B'],\
                   ['1.', '5.65', 'group_C'],\
                   ['9.06', '10.2', 'group_B'],\
                   ['2.', '0.2', 'group_B'],\
                   ['11.', '2.1', 'group_C']])

例如,我在数据的最后一列中有两个组。从每个组中,我想随机提取n 行数(例如1 每组行)。我非常感谢任何帮助我在 Python 中做我想做的事情。

【问题讨论】:

    标签: python numpy random


    【解决方案1】:

    这是您可以做到的一种方式:

    代码

    import numpy as np
    import random
    
    max_items = 2
    my_array=np.array([['1.66', '1.67', 'group_B'],
                       ['1.', '5.65', 'group_C'],
                       ['9.06', '10.2', 'group_B'],
                       ['2.', '0.2', 'group_B'],
                       ['2.', '0.2', 'group_B'],
                       ['2.', '0.2', 'group_C'],
                       ['11.', '2.1', 'group_C']])
    
    classes = np.unique(my_array[:,-1])
    new_array = []
    for cls in classes:
        for i in range(max_items):
            new_array.append(random.choice(my_array[my_array[:,-1]==cls]))
    
    print(*new_array, sep='\n')
    

    输出

    ['2.' '0.2' 'group_B']
    ['2.' '0.2' 'group_B']
    ['2.' '0.2' 'group_C']
    ['1.' '5.65' 'group_C']
    

    【讨论】:

    • 亲爱的@Abhi_J,感谢您出色的解决方案。我有一个问题:max_items 是什么?是我拥有的组数吗? r 是我得到的随机行数吗?
    • @Ali_d,在你的问题中是n 从每个组中,我想随机提取 n 行(例如每组 1 行)
    猜你喜欢
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 2012-03-27
    相关资源
    最近更新 更多