在组合中增加迭代的最有效的方法是什么?

2024-04-25 04:16:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个numpy数组:NxM

比如说:

input_data = np.random.rand(10,5)

我想创建一个新数组,其中新数组是输入数据列之间的所有可能差异,这将为您提供一个大小为:(10,10)的数组

到目前为止,我的代码是:

def get_data_differences(read_data):
    '''Finds every possible differences between the columns of the read_data
    read_data: NxM variable where M are the features
    returns diff_data, and NxR variables
    R is the number of every possible combination of 2 columns

    '''
    if len(read_data.shape) != 2:
        print 'The data format is not consistent'
    data_rows, data_columns = read_data.shape
    data_difference = np.zeros((data_rows, 1))
    for combination_pair in itertools.combinations(read_data.T, 2):
    #iterate over every possible pairing of columns (hence the .T)
        minuend_, substraend_ = combination_pair
        difference_ = minuend_ - substraend_
        data_difference = np.append(data_difference, difference_[:, None], axis = 1)
    data_difference = np.delete(data_difference, 0, 1)
    return data_difference

我发现删除我创建的原始零数组效率不高。你知道吗

如果你有更好的建议,那就太好了


Tags: columnsofthereaddataisnp数组