How does np.array() works internally?
I've written my own tensor library and a corresponding Python binding. And I've made sure iterating through my tensor implementation works exactly like how NumPy works. I also made sure important method calls like __len__
, __getitem__
, __setitem__
, etc... all works like how NumPy expected it to be. And so I expect
t = my_tensor.ones((4, 4))
print(t) # works
a = np.array(t)
print(a) # becomes a 32 dimension array
to give me a 4x4 matrix. But instead it gave me a 4x4x1x1.... (32 dims in total) array. I'm out of ways to debug this problem without knowing how NumPy performs the conversion internally. How does np.array
works internally? I'm unable to locate the function within NumPy's source code nor I can find useful information on the web.
1 answer

Have you tried looking at the official Numpy's documentation? https://numpy.org/doc/stable/contents.html
Questions specific as this one are usually solved by looking at the original library documentation (e.g. https://numpy.org/doc/stable/user/quickstart.html#arraycreation)
See also questions close to this topic

matplotlib.pyplot.imshow: can not correctly show an ndarray with 'float64' dtype
I intend to change the dtype from 'uint' (img) to 'float64' (img509) and use imshow to show that image, but I got the display which is the same as that of img.
import numpy as np import matplotlib.pyplot as plt plt.ion() fname = 'Lena_gray.bmp' # gray level, 512 img = plt.imread(fname) img50 = img+50 img509 = img+50.9 plt.imshow(img, cmap='gray') plt.imshow(img50, cmap='gray') # different from img plt.imshow(img509, cmap='gray') # the same as img

Multiple conditions for list comprehension in Python
I would like to create a column based on values in index:
If index starts with alphabetical value and not 'I0', return "P", otherwise return "C".
Tried:
df['new_col'] = ['P' if (x[0].isalpha() and not x[0].startswith("I0")) else 'C' for x in df.index]
but it returned 'P' for rows which start with
'I0'
:A B C new_col Index I00001 1.325337 4.692308 1.615385 P I00002 1.614780 3.615385 0.769231 P I00003 1.141453 5.461538 2.000000 P I00004 0.918300 8.538462 2.769231 P I00005 1.189606 11.846154 2.692308 P I00006 0.941459 7.153846 2.153846 P I00007 0.466383 12.153846 9.384615 P I00008 0.308627 198.692308 23.461538 P I00011 0.537142 23.384615 6.846154 P I00012 1.217390 11.923077 1.230769 P I00013 1.052840 3.384615 2.000000 P ...
Reproducible example:
df = pd.DataFrame({'A': {'I00001': 1.3253365856660808, 'I00002': 1.6147800817881086, 'I00003': 1.1414534979918203, 'I00004': 0.9183004454646491, 'I00005': 1.1896061362142527, 'I00006': 0.941459102789141, 'I00007': 0.46638312473267185, 'I00008': 0.3086270976042302, 'I00011': 0.5371419441302684, 'I00012': 1.2173904641254587, 'I00013': 1.052839529263679, 'I00014': 1.3587324409735149, 'I00015': 3.464101615137755, 'I00016': 1.1989578808281798, 'I00018': 0.2433560755649686, 'I00019': 0.5510000980337852, 'I00020': 3.464101615137755, 'I00022': 1.0454523047666737, 'I00023': 1.3850513878332371, 'I00024': 1.3314720972390754}, 'B': {'I00001': 4.6923076923076925, 'I00002': 3.6153846153846154, 'I00003': 5.461538461538462, 'I00004': 8.538461538461538, 'I00005': 11.846153846153847, 'I00006': 7.153846153846154, 'I00007': 12.153846153846153, 'I00008': 198.69230769230768, 'I00011': 23.384615384615383, 'I00012': 11.923076923076923, 'I00013': 3.3846153846153846, 'I00014': 1.0, 'I00015': 0.07692307692307693, 'I00016': 0.6153846153846154, 'I00018': 481.7692307692308, 'I00019': 7.3076923076923075, 'I00020': 0.07692307692307693, 'I00022': 1.6153846153846154, 'I00023': 0.5384615384615384, 'I00024': 12.538461538461538}, 'C': {'I00001': 1.6153846153846154, 'I00002': 0.7692307692307693, 'I00003': 2.0, 'I00004': 2.769230769230769, 'I00005': 2.6923076923076925, 'I00006': 2.1538461538461537, 'I00007': 9.384615384615385, 'I00008': 23.46153846153846, 'I00011': 6.846153846153846, 'I00012': 1.2307692307692308, 'I00013': 2.0, 'I00014': 0.38461538461538464, 'I00015': 0.07692307692307693, 'I00016': 0.46153846153846156, 'I00018': 79.07692307692308, 'I00019': 3.6923076923076925, 'I00020': 0.07692307692307693, 'I00022': 1.1538461538461537, 'I00023': 0.46153846153846156, 'I00024': 2.3076923076923075}} )

Can I plug functions created with lambda x on a list? (python)
I need to build a polynomial function like a_0 + a_1x + a_2x^2 ... I am trying to do the whole interpolation process. I have this:
def Create_F(Numero, Array): Y = lambda x: x Lista = list(Array) F_x = [] for i in range(Numero): G_x = lambda x: eval(Lista[i]*Y^i) F_x.append(G_x) return F_x
And if I use this, I do not get nothing that help:
Number = 2 ma = np.array([[1, 1], [1, 2]]) ly = np.array([8, 3]) idk = Create_F(Number, ly) print(idk)
I don't know how to evaluate, for example 1. If I can do this in a better way it would be very helpful, the complete code is:
import numpy as np def Matrix_F(Num, Lx): Vec = np.zeros((Num, Num), dtype = float) Vec.T[1] = Lx ex = 0 for i in range(Num): for j in range(Num): Vec[j][i]=Lx[j]**ex ex += 1 return Vec def Cramer_F(Ma, Ly): Lc, Det = np.array(Ly), np.linalg.det(Ma) col = len(Lc) Values = np.zeros(col) for i in range(col): org = Ma.copy() org.T[i]=Lc Di=np.linalg.det(org) Values[i] = Di/Det error = np.linalg.norm(np.dot(Ma, Values)Lc) return Values, error def Create_F(Numero, Array): Y = lambda x: x Lista = list(Array) F_x = [] for i in range(Numero): G_x = lambda x: eval(Lista[i]*Y^i) F_x.append(G_x) return F_x val = int(input('Ingrese la cantidad de valores de X y Y que posee: ')) x_val = [] y_val = [] print('Ingrese %s valores de cada variable:' %(val)) n = 1 for i in range(val): x = float(input('%s° Valor de x: '%(n))) y = float(input('%s° Valor de y: '%(n))) x_val.append(x) y_val.append(y) n += 1 #Matriz del sistema: As = Matrix_F(val, x_val) #Valores de "a_n" y error a_val, er = Cramer_F(As, y_val) n=0 print() for i in a_val: print('a_%s = %.6f' %(n, i)) n += 1
Thanks you for your time!

How to check whether there are 2 similar columns in a 2D array in C
Write a function that gets a 2d array, its number of rows, its number of columns and checks whether there are 2 similar columns or not. If there are 2 similar columns, it returns true.
int compareArray(int a[],int b[],int size) { int i; for(i=0;i<size;i++){ if(a[i]!=b[i]) return 1; } return 0; } int solution(int row, int column, const int array1[row][column]) { int array2[3]; int x=0; int tru[row]; int temparray[row]; while(x<column){ for (int i=0;i<row;i++){ array2[i] = array1[i][x]; } for (int i=0;i<column;i++){ for (int i=0;i<row;i++){ temparray[i] = array1[i][x]; } int sol = compareArray(array2,temparray,row); if (x != i){ if (sol==0){ return 1; } return 0; } //end of if } x++; } //end of while } //End of function
My code returns all answers as true. How can I correct this code to return only columns that are actually similar??

Trying to copy a 2D dimensional array of objects to another function
I'm trying to copy an array from one class to to another class by passing it to a function but I'm running into issues. The array that I'm trying to copy seems to lose all its data.
// A.h class A public: virtual void Test(); private: A* array2D[30][32];
// A.cpp void A::Test() { B* f = new B(); f>pass(array2D); }
// B.h class A; class B { public: void pass(A *a[][32]); private: A *a[30][32]; }
// B.cpp void B::pass(A *array2D[][32]) { for (int i = 0; i <= 30; i++) { for (int j = 0; j <= 32; j++) { a[i][j] = array2D[i][j]; } } }
My guess is that it's happening when I'm passing it but I'm not sure what I'm doing wrong.

Movement inside 2d array
I have a 2D array map, where the bottom left corner is
[0][0]
:Scanner in = new Scanner(System.in); String [][] map = new String[2][3]; for (int i = 2; i != 0; i){ for (int j = 0; j < 3; j++) { map[i1][j] = in.next(); } }
Ex:
O O O O O X
The
X
represents a tile with a boost andO
a regular tile. Next, it asks for the player name, starting position, how many times to move than the direction in which they are supposed to move:north, east, south or west
The input is supposed to look like this:O O O //board layout O O O O O X sam O X 1 //number of players Sam 0 0 //player name and starting position > O O O 3 //number of movements to make OsamX Sam east //Directions to go in Sam east O O O O O sam Sam north O O sam O O X
If the person moves through the
X
by the end of the movements like in the example above it is supposed to output:Sam, has a boost
If the person never moves through the
X
or after they move 2 more steps after being onX
it's supposed to output:Sam, doesn't have a boost
But I can't seem to get the movement right. I can only get it to move 1 time, I don't know if the for loop is not working or because the old position isn't getting updating. It's also not printing.
int numOfPlayers = in.nextByte(); String playerName= in.next(); int xPosition = in.nextByte(); int yPosition = in.nextByte(); map[xPosition][yPosition ] = playerName; int numOfMovements = in.nextByte(); for (int i = 0; i < numOfMovements; i++) { playerName = in.next(); String diretions = in.next(); if (diretions.equals("north")) { map[xPosition ][Y] = map[xPosition+1][yPosition]; map[xPosition+1][Y] = playerName; if (map[xPosition+1][Y].equals("X") { System.out.println(playerName + ": has a boost"); } else { System.out.println(playerName + ": doesn't have a boost"); } } else if (diretions.equals("east")) { map[xPosition ][yPosition] = map[xPosition ][yPosition+1]; map[xPosition ][yPosition+1] = name; if (map[xPosition ][yPosition+1].equals("X") { System.out.println(playerName + ": has a boost"); } else { System.out.println(playerName + ": doesn't have a boost"); } } }
Can anyone help, Thank you.

Creating Numpy structured array
While brushing up my numpy skills, I've encounter the structured array.
>>> import numpy as np >>> person_data_def = [('name', 'S6'), ('height', 'f8'), ('weight', 'f8'), ('age', 'i8')] >>> person_data_def [('name', 'S6'), ('height', 'f8'), ('weight', 'f8'), ('age', 'i8')]
What are
S6
,f8
andi8
in this context? 
Numpy get values at indices given in array form
I want to get the values at
indices
ofmy_array
.indices = np.array([[[0], [1], [0]]]) my_array = np.array([[[1.1587323 , 1.75406635], [1.05464125, 1.29215026], [0.9784655 , 1.16957462]]])
I should get the following output:
output: array([[[1.1587323], [1.29215026], [0.9784655]]])
Is it possible without for loops or list comprehensions?

Which is the fastest method to calculate means square error in large image dataset?
I'm trying to calculate the mean square error in an image dataset(CIFAR10). I have a
numpy array
of dimension5*10000*32*32*3
which is, in words, 5 batches of 10000 images each with dimensions of32*32*3
. These images belong to 10 categories of images. I have calculated average of each class and now I'm trying to calculate the mean square error of each of the 50000 images wrt the 10 average images. Here is the code:for i in range(0, 5): for j in range(0, 10000): min_diff, min_class = float('inf'), 0 for avg in class_avg: # avg class comprises of 10 average images temp = mse(avg[1], images[i][j]) if temp < min_diff: min_diff = temp min_class = avg[0] train_pred[i][j] = min_class
Problem: Is there any way to make it faster. Any numpy magic? Thank you.