使用numpy从python中的数组中提取子数组

时间:2017-10-10 03:51:49

标签: python arrays numpy

如果这是在家庭作业上给出的:

string[] delimiterChars = new string[] {"\\","r","n","tdevice"};
string y = output.Substring(z+1);
string[] words;
words = y.Split(delimiterChars, StringSplitOptions.None);

任务是:

编写一个表达式,从room_matrix中检索以下子矩阵:

import numpy as np
room_matrix = \
np.array(
[[6,  3, 4, 1],
[5,  2, 3, 2],
[8,  3, 6, 2],
[5,  1, 3, 1],
[10, 4, 7, 2]])

到目前为止我已经这样做了:

array([[2,3],
      [3,6]])
然后我打印" a"和" b"输出是:

a=room_matrix[1,1:3]
b=room_matrix[2,1:3]

但我希望它们像一个真正的子阵列一样执行:

[2 3]
[3 6]

我可以连接" a"和" b"?或者是否有另一种方法来提取子数组,以便输出实际上将其显示为数组,而不仅仅是我打印两个拼接?我希望这是有道理的。谢谢。

3 个答案:

答案 0 :(得分:1)

你不需要两行。 Numpy允许您在单个语句中拼接,如下所示:

import pandas as pd

@app.route('/', methods=['GET', 'POST'])
    def upload_file():
        if request.method == 'POST':
            file = request.files['file']
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

                ## snippet to read code below
                file.stream.seek(0) # seek to the beginning of file
                myfile = file.file # will point to tempfile itself
                dataframe = pd.read_csv(myfile)
                ## end snippet

                return "yatta"
            else:
                return "file not allowed"

        return render_template("index.html")

答案 1 :(得分:1)

这个怎么样:

room_matrix[1:3, 1:3]
#will slice rows starting from 1 to 2 (row numbers start at 0), likewise for columns

答案 2 :(得分:0)

这个问题已经得到了回答,所以只是将它扔出去,但实际上,你可以使用np.vstack来连接"你的a和b矩阵得到了预期的结果:

In [1]: import numpy as np

In [2]: room_matrix = \
...: np.array(
...: [[6,  3, 4, 1],
...: [5,  2, 3, 2],
...: [8,  3, 6, 2],
...: [5,  1, 3, 1],
...: [10, 4, 7, 2]])

In [3]: a=room_matrix[1,1:3]

In [4]: b=room_matrix[2,1:3]

In [5]: np.vstack((a,b))
Out[5]: 
array([[2, 3],
       [3, 6]])