18 ms·
NumPy Illustrated: The Visual Guide to NumPy
- platelets2020 6y agoAs far as I can tell, this "visual guide" is nothing more than: 1. Taking screenshots of code. 2. Taking screenshots of code and putting the array values inside of blue boxes.
- andai 6y agoNeed it be more?
- randomfool 6y agoYes! Text which can be copy pasted!
- axi1 6y ago3245 words should be more than enough for that :) My greatest concern about the text that it would be too much of it for something called "Visual Guide", so I tried hard to keep it to bare minimum.
- turndown 6y agoThe second half of #2 qualifies as fine art to my meager artistic abilities.
- axi1 6y agoActually, it also has 3. A thought-provoking text in between, but apparently didn't hit the target in your case.
- Ultcyber 6y agoYes. Does it mean it's bad? For people that just start to learn the library, it's sometimes useful to have a visual representation. Also, helpful to have a list of main features.
- jsinai 6y agoWow those diagrams are extremely well thought out and clear to understand. Saying they’re just blue boxes is a huge understatement. Visualising highly conceptual topics like numerical programming is not an easy skill, and the more the better.
- systemvoltage 6y agoYour comment is just a bunch of letters typed out as words in a sentence without any sort of insight and just providing a reductionist view. It’s so much more than that. This is not what HN community is about.
- tgb 6y agoOne thing to add: the search section is missing the argsort function, which is invaluable in my experience. It's how you work around the lack of key sorting, for example. Edit: though now I see it is brought up later on in the matrix section.
- Niccizero 6y agoArchive.is link: https://archive.is/WAZKr https://archive.is/WAZKr
- axi1 6y agoFriends link: https://medium.com/better-programming/numpy-illustrated-the-visual-guide-to-numpy-3b1d4976de1d?source=friends_link&sk=57b908a77aa44075a49293fa1631dd9b https://medium.com/better-programming/numpy-illustrated-the-...
- amznbyebyebye 6y agoWow this is great. Perfect example of how something simple like this can be super helpful to new users. I learn super well when there’s lots of visuals. Thanks!!!
- proverbialbunny 6y ago>Careful though; Python “ternary” comparisons like 3<=a<=5 don’t work here. Anyone have any idea why? I imagine if they could support it they would support it. I wonder if Python doesn't allow this kind of operator overloading?
- pansa2 6y ago`3 <= a <= 5` expands to `3 <= a and a <= 5`. However, based on the examples NumPy seems to require `&` instead of `and` - I’m not sure why.
- Pinus 6y agoA type can't implement its own 'and' and 'or' operators. (Probably because it is non-obvious how to handle their short-circuiting behaviour.)
- axi1 6y agoApparently there're problems with overloading this. In pandas it is between(left,right), so they also didn't find a way to get it done properly.
- adamjb 6y agoHere's the rejected PEP for operator overloading. https://www.python.org/dev/peps/pep-0335/ https://www.python.org/dev/peps/pep-0335/ and deferred PEP for rich comparison chaining specifically https://www.python.org/dev/peps/pep-0535/ https://www.python.org/dev/peps/pep-0535/ The central issue is that `3<=a<=5` expands to `3<=a and a<=5`, and `and` coerces the variables to booleans in order to work.
- proverbialbunny 6y ago>and deferred PEP for rich comparison chaining specifically >https://www.python.org/dev/peps/pep-0535/ https://www.python.org/dev/peps/pep-0535/ Oh nice! Thank you for sharing. I'm sure the functionality will eventually come.
- 6y ago
- baby 6y agoFlagged due to soft paywall
- axi1 6y agoThere're two ways to walk it around in the comments here: friends link and archive.is
- blackbear_ 6y agoDisabled javascript also works
- jasode 6y ago>Disabled javascript also works This isn't true. I just tested it with Javascript disabled. After about 5 articles, the text is greyed out and you can't read the rest of of the article: https://imgur.com/a/KCF9yPE https://imgur.com/a/KCF9yPE
- blackbear_ 6y agoTry to disable cookies as well ;)
- sirpunch 6y agoProbably I'm not reading it right. In 2D, .sum(axis=0) operation is column-wise but for .insert() and .delete() it seems row-wise?
- deleted 6y ago[deleted]
- sirpunch 6y agoI mean the insert and delete operations with axis value set to 0.
- axi1 6y agoIt probably makes more sense if you think of matrices as n-dimentional arrays: sum eliminates the n-th dimention, insert and delete increase or decrease the n-th dimension size.
- giu 6y agoVery good point. Additionally, with insert and delete we might need to apply the rules of broadcasting [0]. For example, if I have a 2-dimensional array and I insert a scalar value by using axis=0, the scalar value needs to be broadcasted to match the column dimension of the array: >>> a = np.array([[1,2],[3,4],[5,6]]) >>> np.insert(a, 1, 11, axis=0) array([[ 1, 2], [11, 11], [ 3, 4], [ 5, 6]]) [0] https://jakevdp.github.io/PythonDataScienceHandbook/02.05-computation-on-arrays-broadcasting.html#Rules-of-Broadcasting https://jakevdp.github.io/PythonDataScienceHandbook/02.05-co...
- Schiphol 6y agoThis is fantastic, I will share it with students. A very minor comment: >So, there’s a total of three types of vectors in NumPy: 1D arrays, 2D row vectors, and 2D column vectors. I think you can have 'vectors' of arbitrarily high dimension, by adding empty axes, or doing, say, .reshape(-1, 1, 1, 1). I would also tie this point with the rule for broadcasting that dimensions which do not match need to have a value of one. I'm endlessly confused about broadcasting, and find the explicit rule useful.
- zhd 6y agoAlas, Numpy arrays are limited to thirty-two dimensions. This is fine, because with high numbers of dimensions you really can't afford to store a dense-matrix representation in RAM and 32 is plenty for any low-dimensional problem.
- axi1 6y agoThanks, good point! I'll think how to fit it best into the article.
- axi1 6y agoI've finally fixed the article, thanks. Yes, broadcasting is a cool thing, but the docs mostly explains 'how' but not 'why' or 'what for'.
- Schiphol 6y agoI'm glad I could be of help! > Yes, broadcasting is a cool thing, but the docs mostly explains 'how' but not 'why' or 'what for'. I'd say that, even for the 'how', thinking "OK, I have a [1, 1, 2, 2, 1] and a [3, 2, 1, 2, 5] arrays, which means that element-wise multiplication would result in a [3, 2, 2, 2, 5] array" is very useful in reasoning about broadcasting. Just relying on simple examples and trying to build an intuition for the general case (which is the route favored in the numpy docs, I'd say) doesn't quite work, at least for me.
- fouronnes3 6y agoI like to stop and appreciate the ndarray abstraction. It's a really beautiful interface that hits all the right spots to me. Anytime I'm working with numerical data in a language without an ndarray I miss it quite strongly. Indexing, slices, broadcasting... it's all so brilliant.
- sleavey 6y agoAgreed. I occasionally imagine a feature that it would be cool to have in Numpy, then find that it's already there. Most recently I discovered (somewhat lately) that you can create arbitrarily structured arrays and store things like strings alongside array elements [1]. [1] https://numpy.org/doc/stable/user/basics.rec.html https://numpy.org/doc/stable/user/basics.rec.html
- enriquto 6y agoAs a counterpoint, if you are used to real, language-supported numerical arrays, then numpy's ndarray seems like a joke.
- emmelaich 6y agoelaborate please
- Jenz 6y agoThis must have piqued a number of readers interedts, mine included. Are you reffering to something like Matlab? Julia?
- enriquto 6y agoThere's many programming languages where multidimensional arrays of floats are a natural language construct. From low-level (e.g. Fortran) to high level languages (e.g. Octave/Matlab, Julia). Even in C you can work with multidimensional arrays of floats, but it is a bit cumbersome. This is not the case for Python, where the language cannot express in itself this data structure, and it needs external library support like numpy. EDIT: I'm always very surprised by the wide acceptance of python/numpy for numerical algorithms, as it seems a notion quite foreign and awkward for this language. Python has excellent native support for string processing and advanced data structures like dictionaries, but those are mostly useless for numerical computation. If you want to do math in Python, you need to write libraries in other languages and provide a Phython interface. This is what scipy does, and it is a very good job, but it does not feel "natural" from the point of view of the language. If Python was a good scientific programming language, the most natural way to implement scipy/numpy and all that would be using Python itself, but this is not at all the case.
- knolan 6y agoI guess it isn’t popular in these parts, but there is a simplicity to Matlab that’s hard to beat for lowly mechanical engineers. The documentation is also generally excellent. Unfortunately most undergraduates get locked in early with free student versions and continue to use it in industry. Currently I’m trying to expose my students to both Matlab and Python/numpy in a matter of fact manner.
- enriquto 6y ago> Unfortunately most undergraduates get locked in early with free student versions and continue to use it in industry. Why no octave? Or julia?
- deleted 6y ago[deleted]
- divtiwari 6y agoI'm afraid Julia will always be ignored in favour of Python. Python/C++ have a firm grip over its niche for years to come.
- pc86 6y agoI think the question is "why Julia?" instead of "why not Julia?" Python is the de facto standard, for better or worse. If someone wants to unseat it, they need a compelling reason. You shouldn't put the onus on folks defaulting to the industry standard to justify their choice over a much less well-known competitor.
- Ultcyber 6y ago(in np.sum) > The value of the axis argument is, as a matter of fact, the number of the index in question: The first index is axis=0, the second one is axis=1, and so on If I'm not wrong - this statement is wrong - the axis does not represent index (or otherwise it would be axis 0 = row, axis 1 = column). The actual idea behind is a little unintuitive, but explained well here: https://aerinykim.medium.com/numpy-sum-axis-intuition-6eb94926a5d1 https://aerinykim.medium.com/numpy-sum-axis-intuition-6eb949...
- Schiphol 6y agoThe usual matrix notation is a_ij for the element in the ith row and the jth column. If you order axes in this way you get the numpy convention.
- Ultcyber 6y agothat's what I mean - in this sense, the axis 0 should be row, but instead it's column in numpy
- svara 6y agoIt's explained in more detail further down in that paragraph, I think the wording is fine. The axis argument gives the index of the axis along which your summate, and which therefore disappears after summation. There might be a confusion about whether "axis 0" is rows or columns? Its length is the number of rows, but it "points" along columns. I prefer just calling them axis 0, 1, 2, ... and avoid thinking about rows and columns in numpy, I've found that sometimes avoids confusion.
- febstar 6y agoIs the random matrix generation section in here up to date? The official numpy docs [0] seem to indicate that `randn` is legacy, and that `randint` is deprecated. [0] https://numpy.org/doc/stable/reference/random/index.html https://numpy.org/doc/stable/reference/random/index.html
- axi1 6y agoYes, I'm aware that are preparing a mini-revolution in the random number generation. But I was waiting for the interface to settle down a bit prior to including it. I didn't know they were officially deprecated though, thanks for the info! Actually, I don't believe they will ever remove those legacy functions, though, as matlab is still way more popular than numpy overall.
- metalrain 6y agoGreat article full of examples, learned quite a bit new things. Personally I don't quite get why something like a[a > 5] = 0 is possible (a is NumPy array). I think it is confusing to use same name for element wise comparison and the array itself. Are comparison operators overloaded to generate this kind of predicate function or view in other contexts as well or is this some sort of special case that is handled by indexing (__getitem__ call)?
- Schiphol 6y agoa > 5 results in a boolean array, via 'broadcasting'. These are rules that allow numpy to interpret the 5 as an array with the same dimensions as a, but full of 5s.
- niklasbuschmann 6y agoIt’s the array accessing that is overloaded. a > 5 is a boolean array with the same dimension as a, and now the overloaded method for array access gets called with this boolean array. I also found it incredibly confusing the first time I saw this, but like all the numpy magic based on overloading, it’s confusing the first time you see it, but incredibly handy afterwards.
- metalrain 6y agoThat kind of makes sense. You use logical expressions to build mask that you use to generate view in the outer expression.
- fantod 6y agoBoth are overloaded (__gt__ and __getitem__). My question to you is: How would expect this to be written (in Python)?
- metalrain 6y agoI guess lambda is too verbose a[lambda i: i > 5] = 0 Probably would expect something like this np.set(a, lambda i: i > 5, 0) But that might be too cumbersome when combining values from multiple arrays.
- deleted 6y ago[deleted]
- tobmlt 6y agoI have a friend who complains that that it would be nice, on some occasions, to specify the shape of the result from a numpy computation. -that it is all to easy to duck type your way into a linear algebra bug that isn’t easily caught. My response is that, in those cases, go ahead and declare the array you want to catch the result (and it’s shape), then use [:] etc. appropriately to ensure that if the size doesn’t match between computed and expected at the point of assignment, it will fail.
- geoalchimista 6y agoOff-topic: I couldn't help noticing that there is such a recurrent pattern that under every NumPy-related topic, there are fervent disciples of Julia who prophecy that the end (of Python) is nigh and you should all be converting to Julia. But why not use whatever suits your problem the best? I use both Python and Julia in my research, and sometimes R when I need some niche statistical packages. "My language is superior to your language" is such a self-limiting mindset.
- dklend122 6y agoIt wasn't too long ago that the reverse happened. People are excited about Julia, because frankly it's amazing and a breath of fresh air coming from python. Also, it's really now starting to pick up steam. Curious though, how are limited by using Julia? Any python or r package is a pycall/rcall away. Otherwise it's faster, more ergonomic and makes coding fun again