Created
September 14, 2014 21:10
-
-
Save kanungo/a6a1638493061ca36826 to your computer and use it in GitHub Desktop.
Shaping and slicing numpy arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"metadata": { | |
"name": "" | |
}, | |
"nbformat": 3, | |
"nbformat_minor": 0, | |
"worksheets": [ | |
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"import numpy as np\n", | |
"myarray = np.reshape(np.arange(16),(4,4))\n", | |
"\n", | |
"# Accessing specific part of matrix a\n", | |
"# a. Four elements in the north-west corner\n", | |
"# b. Four elements in the middle\n", | |
"# c. Four elements in the south-east corner\n", | |
"\n", | |
"a = myarray[0:2,0:2]\n", | |
"b = myarray[1:3,1:3]\n", | |
"c = myarray[2:,2:]\n", | |
"\n", | |
"print 'a'\n", | |
"print a\n", | |
"print 'b'\n", | |
"print b\n", | |
"print 'c'\n", | |
"print c\n" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [] | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"# Create a 4x3 array\n", | |
"# Obtain the sum of each row\n", | |
"# Obtain the sum of each column\n", | |
"\n", | |
"a = np.reshape(np.arange(9),(3,3))\n", | |
"\n", | |
"# for row sums\n", | |
"for r in range(a.shape[0]):\n", | |
"\tprint sum(a[r,:])\n", | |
"\n", | |
" # for column sums\n", | |
"for r in range(a.shape[1]):\n", | |
"\tprint sum(a[:,r])\n" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [] | |
} | |
], | |
"metadata": {} | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment