Skip to main content
Filter by
Sorted by
Tagged with
925 votes
23 answers
1.3m views

When I print a numpy array, I get a truncated representation, but I want the full array. >>> numpy.arange(10000) array([ 0, 1, 2, ..., 9997, 9998, 9999]) >>> numpy.arange(...
kame's user avatar
  • 22.3k
837 votes
21 answers
812k views

NumPy proposes a way to get the index of the maximum value of an array via np.argmax. I would like a similar thing, but returning the indexes of the N maximum values. For instance, if I have an array, ...
Alexis Métaireau's user avatar
827 votes
13 answers
1.4m views

How do I dump a 2D NumPy array into a csv file in a human-readable format?
Dexter's user avatar
  • 11.9k
810 votes
26 answers
1.5m views

I have two points in 3D space: a = (ax, ay, az) b = (bx, by, bz) I want to calculate the distance between them: dist = sqrt((ax-bx)^2 + (ay-by)^2 + (az-bz)^2) How do I do this with NumPy? I have: ...
Nathan Fellman's user avatar
718 votes
17 answers
1.7m views

How do I convert a Pandas dataframe into a NumPy array? import numpy as np import pandas as pd df = pd.DataFrame( { 'A': [np.nan, np.nan, np.nan, 0.1, 0.1, 0.1, 0.1], 'B': [0.2, ...
Mister Nobody's user avatar
714 votes
12 answers
1.2m views

What is the most efficient way to map a function over a numpy array? I am currently doing: import numpy as np x = np.array([1, 2, 3, 4, 5]) # Obtain array of square of each element in x squarer = ...
Ryan's user avatar
  • 8,351
695 votes
12 answers
727k views

A 2D array can be reshaped into a 1D array using .reshape(-1). For example: >>> a = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8]]) >>> a.reshape(-1) array([[1, 2, 3, 4, 5, 6, 7, 8]]) ...
user2262504's user avatar
  • 7,417
686 votes
10 answers
1.3m views

Given: test = np.array([[1, 2], [3, 4], [5, 6]]) test[i] gives the ith row (e.g. [1, 2]). How do I access the ith column? (e.g. [1, 3, 5]). Also, would this be an expensive operation?
lpl's user avatar
  • 6,909
678 votes
32 answers
1.2m views

How do I count the number of 0s and 1s in the following array? y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]) y.count(0) gives: numpy.ndarray object has no attribute count
mflowww's user avatar
  • 7,515
677 votes
24 answers
1.2m views

I know there is a method for a Python list to return the first index of something: >>> xs = [1, 2, 3] >>> xs.index(2) 1 Is there something like that for NumPy arrays?
Nope's user avatar
  • 36.2k
598 votes
14 answers
837k views

df = pd.read_csv('somefile.csv') ...gives an error: .../site-packages/pandas/io/parsers.py:1130: DtypeWarning: Columns (4,5,7,16) have mixed types. Specify dtype option on import or set low_memory=...
Josh's user avatar
  • 12.9k
587 votes
8 answers
1.0m views

I have a pandas dataframe with multiple columns. I want to change the values of the only the first column without affecting the other columns. How can I do that using apply() in pandas?
Amani's user avatar
  • 18.6k
580 votes
14 answers
1.3m views

Is there a direct way to import the contents of a CSV file into a record array, just like how R's read.table(), read.delim(), and read.csv() import data into R dataframes? Or should I use csv.reader() ...
hatmatrix's user avatar
  • 45.5k
574 votes
8 answers
264k views

What are the advantages of NumPy over regular Python lists? I have approximately 100 financial markets series, and I am going to create a cube array of 100x100x100 = 1 million cells. I will be ...
Thomas Browne's user avatar
520 votes
16 answers
566k views

How do I sort a NumPy array by its nth column? For example, given: a = array([[9, 2, 3], [4, 5, 6], [7, 0, 5]]) I want to sort the rows of a by the second column to obtain: ...
user avatar
517 votes
12 answers
785k views

What does np.random.seed do? np.random.seed(0)
covariance's user avatar
  • 7,303
510 votes
15 answers
870k views

How do I add a color column to the following dataframe so that color='green' if Set == 'Z', and color='red' otherwise? Type Set 1 A Z 2 B Z 3 B X 4 C Y
user7289's user avatar
  • 34.6k
505 votes
10 answers
380k views

What is the purpose of np.meshgrid? I know it creates some kind of grid of coordinates for plotting, but I can't see the direct benefit of it. The official documentation gives the following example, ...
HonzaB's user avatar
  • 7,405
499 votes
21 answers
630k views

How do I find the nearest value in a numpy array? Example: np.find_nearest(array, value)
Fookatchu's user avatar
  • 7,475
497 votes
8 answers
988k views

How do I convert a PIL Image back and forth to a NumPy array so that I can do faster pixel-wise transformations than PIL's PixelAccess allows? I can convert it to a NumPy array via: pic = Image.open(&...
akdom's user avatar
  • 33.5k
494 votes
14 answers
674k views

How do I print formatted NumPy arrays in a way similar to this: x = 1.23456 print('%.3f' % x) If I want to print the numpy.ndarray of floats, it prints several decimals, often in 'scientific' format, ...
camillio's user avatar
  • 4,955
483 votes
14 answers
913k views

How do I convert a numpy.datetime64 object to a datetime.datetime (or Timestamp)? In the following code, I create a datetime, timestamp and datetime64 objects. import datetime import numpy as np ...
Andy Hayden's user avatar
480 votes
17 answers
595k views

After creating a NumPy array, and saving it as a Django context variable, I receive the following error when loading the webpage: array([ 0, 239, 479, 717, 952, 1192, 1432, 1667], dtype=int64) ...
Karnivaurus's user avatar
  • 24.4k
474 votes
8 answers
203k views

What is the difference between NumPy's np.array and np.asarray? When should I use one rather than the other? They seem to generate identical output.
Benjamin Hodgson's user avatar
465 votes
9 answers
807k views

What is the simplest way to compare two NumPy arrays for equality (where equality is defined as: A = B iff for all indices i: A[i] == B[i])? Simply using == gives me a boolean array: >>> ...
clstaudt's user avatar
  • 22.7k
463 votes
17 answers
871k views

Given the following 2D array: a = np.array([ [1, 2, 3], [2, 3, 4], ]) I want to add a column of zeros along the second axis to get: b = np.array([ [1, 2, 3, 0], [2, 3, 4, 0], ])
Peter Smit's user avatar
460 votes
4 answers
146k views

import numpy as np y = np.array(((1,2,3),(4,5,6),(7,8,9))) OUTPUT: print(y.flatten()) [1 2 3 4 5 6 7 8 9] print(y.ravel()) [1 2 3 4 5 6 7 8 9] Both function return the ...
cryptomanic's user avatar
  • 6,346
458 votes
17 answers
1.6m views

I want to create an empty array and append items to it, one at a time. xs = [] for item in data: xs.append(item) Can I use this list-style notation with NumPy arrays?
Ben's user avatar
  • 68.9k
450 votes
10 answers
1.1m views

How do I get the dimensions of an array? For instance, this is 2x2: a = np.array([[1, 2], [3, 4]])
Cristi P's user avatar
  • 6,241
450 votes
7 answers
220k views

What are the advantages and disadvantages of each? From what I've seen, either one can work as a replacement for the other if need be, so should I bother using both or should I stick to just one of ...
levesque's user avatar
  • 8,954
447 votes
24 answers
1.0m views

I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.
M456's user avatar
  • 5,857
444 votes
10 answers
1.4m views

I have a Numpy array consisting of a list of lists, representing a two-dimensional array with row labels and column names as shown below: data = np.array([['','Col1','Col2'],['Row1',1,2],['Row2',3,4]])...
user3132783's user avatar
  • 5,505
444 votes
7 answers
719k views

How do I convert a NumPy array into a Python List?
Alex Brooks's user avatar
  • 5,453
438 votes
8 answers
249k views

In numpy, some of the operations return in shape (R, 1) but some return (R,). This will make matrix multiplication more tedious since explicit reshape is required. For example, given a matrix M, if we ...
clwen's user avatar
  • 21k
432 votes
3 answers
278k views

I am trying to implement a "Digit Recognition OCR" in OpenCV-Python (cv2). It is just for learning purposes. I would like to learn both KNearest and SVM features in OpenCV. I have 100 samples (i.e. ...
Abid Rahman K's user avatar
422 votes
7 answers
593k views

How do I concatenate two one-dimensional arrays in NumPy? I tried numpy.concatenate: import numpy as np a = np.array([1, 2, 3]) b = np.array([4, 5]) np.concatenate(a, b) But I get an error: ...
highBandWidth's user avatar
421 votes
11 answers
1.9m views

Let x be a NumPy array. The following: (x > 1) and (x < 3) Gives the error message: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() How ...
Homunculus Reticulli's user avatar
411 votes
9 answers
755k views

I need to create a NumPy array of length n, each element of which is v. Is there anything better than: a = empty(n) for i in range(n): a[i] = v I know zeros and ones would work for v = 0, 1. I ...
max's user avatar
  • 52.7k
405 votes
17 answers
588k views

How do I efficiently obtain the frequency count for each unique value in a NumPy array? >>> x = np.array([1,1,1,2,2,2,5,25,1,1]) >>> freq_count(x) [(1, 5), (2, 3), (5, 1), (25, 1)]
Abe's user avatar
  • 24.2k
404 votes
6 answers
228k views

What is the difference between ndarray and array in NumPy? Where is their implementation in the NumPy source code?
flxb's user avatar
  • 4,575
402 votes
10 answers
588k views

How do I drop nan, inf, and -inf values from a DataFrame without resetting mode.use_inf_as_null? Can I tell dropna to include inf in its definition of missing values so that the following works? df....
user avatar
396 votes
5 answers
527k views

What is numpy.newaxis and when should I use it? Using it on a 1-D array x produces: >>> x array([0, 1, 2, 3]) >>> x[np.newaxis, :] array([[0, 1, 2, 3]]) >>> x[:, np....
Yue Harriet Huang's user avatar
396 votes
13 answers
510k views

If I have a numpy dtype, how do I automatically convert it to its closest python data type? For example, numpy.float32 -> "python float" numpy.float64 -> "python float" numpy.uint32 -> "...
conradlee's user avatar
  • 13.9k
393 votes
13 answers
883k views

How do I remove NaN values from a NumPy array? [1, 2, NaN, 4, NaN, 8] ⟶ [1, 2, 4, 8]
Dax Feliz's user avatar
  • 13k
391 votes
17 answers
764k views

How can I check which version of NumPy I'm using?
larus's user avatar
  • 4,587
380 votes
8 answers
202k views

How does np.einsum work? Given arrays A and B, their matrix multiplication followed by transpose is computed using (A @ B).T, or equivalently, using: np.einsum("ij, jk -> ki", A, B)
Lance Strait's user avatar
  • 4,321
380 votes
8 answers
640k views

Believe it or not, after profiling my current code, the repetitive operation of numpy array reversion ate a giant chunk of the running time. What I have right now is the common view-based method: ...
nye17's user avatar
  • 13.5k
378 votes
11 answers
960k views

I have created an array thusly: import numpy as np data = np.zeros( (512,512,3), dtype=np.uint8) data[256,256] = [255,0,0] What I want this to do is display a single red dot in the center of a ...
jlswint's user avatar
  • 3,893
374 votes
27 answers
447k views

I have a pandas dataframe in which one column of text strings contains comma-separated values. I want to split each CSV field and create a new row per entry (assume that CSV are clean and need only be ...
Vincent's user avatar
  • 18.3k
369 votes
4 answers
470k views

How do I convert a float NumPy array into an int NumPy array?
Shan's user avatar
  • 19.3k

1
2 3 4 5
2306