用x个随机值填充numpy数组

时间:2018-11-17 17:53:09

标签: python numpy

我有一个大小为x的numpy数组,我需要用700 true填充。

例如:

a = np.zeros(5956)

如果我想用70%的True填充,我可以这样写:

msk = np.random.rand(len(a)) < 0.7
b = spam_df[msk]

但是,如果我确实需要700个真实值,而其余的则为假,该怎么办?

2 个答案:

答案 0 :(得分:3)

import numpy as np

x = 5956
a = np.zeros((x), dtype=bool)

random_places = np.random.choice(x, 700, replace=False)
a[random_places] = True

答案 1 :(得分:2)

@implementation nextViewController
{
    NSArray *tableData;
    NSArray * arrayfortable;
    NSMutableArray * selectedIndexpath;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{ 
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];

    NSMutableArray *selectedIndexpath = [[NSMutableArray alloc]init];
    selectedIndexpath = [selectedIndexpath arrayByAddingObject:[tableData objectAtIndex:indexPath.row]];

    NSLog(@"selected",selectedIndexpath);

    if (cell.accessoryType == UITableViewCellAccessoryNone) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        __selectedPath = indexPath;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
        __selectedPath = nil;
    }
}

示例-数组中应该有5个元素,其中3个为True,其余为False。

import numpy as np
zeros = np.zeros(5956-700, dtype=bool)
ones=np.ones(700, dtype=bool)
arr=np.concatenate((ones,zeros), axis=0, out=None)
np.random.shuffle(arr)#Now, this array 'arr' is shuffled, with 700 Trues and rest False