基于用户输入的numpy数组操作

时间:2019-03-26 13:05:29

标签: python arrays numpy

我有一个二维的numpy数组。可以说:

abc = np.arange(40).reshape(10,4)

现在,我接受用户输入的字符串变量'mm'。此变量确定我要对数组执行的操作。它具有以下四个可能的值:

'min':返回包含所有最小值的列

'max':返回具有所有最大值的列

“平均值”:返回包含所有平均值的列

'time':返回具有特定列值的列。它还需要用户的额外输入;列号为变量“ idx”。

我通过定义选择相关功能的字典变量来包括前三种可能性。

dict = {'mean':np.mean, 'max':np.max, 'min':np.min}
fn = dict[mm]

因此,我的输出变量将是:

op = fn(abc,axis=1)

但是,当我尝试包括根据用户输入对特定列进行切片的第四种可能性时,我陷入了困境。是否可以在字典“ dict”中定义任何可以包含此操作的numpy函数?

我不希望使用if-else条件,因为它会使代码太长。实际变量要大得多,处理起来也要复杂得多。

用户变量“ mm”具有不同值时的预期结果:

op_min = np.min(abc,axis=1)
op_max = np.max(abc,axis=1)
op_mean = np.mean(abc,axis=1)
op_time = abc[:,2]  # assuming the user input for idx is 2

2 个答案:

答案 0 :(得分:2)

如果可以转置矩阵,则此函数可以选择一行:

abc = np.arange(40).reshape(10,4)
row_num = 2
f = operator.itemgetter(row_num)
f(abc)

您还可以通过lambda定义一个行函数来选择一列:

f = lambda x: x[:,column_num]
f(abc)

答案 1 :(得分:0)

好的,我找到了解决方案。我按照user3371603的建议转置了矩阵,并使用了operator.getitem函数。然后,我使用了默认值为0的索引变量(idx)。

function endpointsToOneString() {
    var requestOne = new Promise(function(resolve, reject){
        const Http = new XMLHttpRequest();
        const url = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
        Http.open("GET", url);
        Http.onload = function () {
        if (this.status >= 200 && this.status < 300) {
            resolve(Http.response);
        } else {
            reject({
            status: this.status,
            statusText: Http.statusText
            });
        }
        };
        Http.onerror = function () {
        reject({
            status: this.status,
            statusText: Http.statusText
        });
        };
        Http.send();
    });

    var requestTwo = new Promise(function(resolve, reject){
        const HttpTwo = new XMLHttpRequest();
        const urlTwo = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
        HttpTwo.open("GET", urlTwo);
        HttpTwo.onload = function () {
        if (this.status >= 200 && this.status < 300) {
            resolve(HttpTwo.response);
        } else {
            reject({
            status: this.status,
            statusText: HttpTwo.statusText
            });
        }
        };
        HttpTwo.onerror = function () {
        reject({
            status: this.status,
            statusText: HttpTwo.statusText
        });
        };
        HttpTwo.send();
    });


    Promise.all([
        requestOne,
        requestTwo
    ]).then(function(result){
    	var response = JSON.parse(result[0]).join();
      response += JSON.parse(result[1]).join();
      console.log(response);
    });
}
endpointsToOneString();

特别感谢user3371603!

相关问题