how can i adjust space between elements of numpy array? - python

I want such type of output
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. 1.]]
But I am getting This
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
My code is this :
import numpy
print(numpy.identity(size))

This should do the trick:
numpy.set_printoptions(formatter={'all': lambda x: " {:.0f} ".format(x)})
If you want to add the decimal point replace " {:.0f} " by " {:.0f}. "
You can modify the number of spaces or formatting in general in the lambda function.

use numpy.arrange(start, stop, size)
as follow
import numpy as np
arr1 = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 0]])
arr2 = np.arange(1, 9, 1)
print(arr2)
output
[1 2 3 4 5 6 7 8]

Related

Make a graph in python from an incidency matrix

I have created this incidency matrix in python using the following code:
import networkx as nx
nodes = [1, 2, 3, 4, 5, 6]
edges = [[1, 2], [1, 3], [1, 5], [2, 3], [2, 4], [3, 4], [3, 5], [4, 6], [5, 6]]
G = nx.DiGraph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
incidence_matrix = -nx.incidence_matrix(G, oriented=True)
print(incidence_matrix.toarray())
which had returned me this output:
[[ 1. 1. 1. 0. 0. 0. 0. 0. 0.]
[-1. 0. 0. 1. 1. 0. 0. 0. 0.]
[ 0. -1. 0. -1. 0. 1. 1. 0. 0.]
[ 0. 0. 0. 0. -1. -1. 0. 1. 0.]
[ 0. 0. -1. 0. 0. 0. -1. 0. 1.]
[ 0. 0. 0. 0. 0. 0. 0. -1. -1.]]
I wanted to plot the graph of this matrix but unfortunatelly I have no Idea about how can I make it. Could someone help me?
Hi I'm not entirely sure what you mean - is this what you want (see image below)?
This is probably the easiest way to visulise a 2d array.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
im = ax.pcolormesh(incidence_matrix.toarray()) #plot matrix
plt.colorbar(im, ax=ax) #add colorbar
plt.show()

Matrix element repetition bug

I'm trying to create a matrix that reads:
[0,1,2]
[3,4,5]
[6,7,8]
However, my elements keep repeating. How do I fix this?
import numpy as np
n = 3
X = np.empty(shape=[0, n])
for i in range(3):
for j in range(1,4):
for k in range(1,7):
X = np.append(X, [[(3*i) , ((3*j)-2), ((3*k)-1)]], axis=0)
print(X)
Results:
[[ 0. 1. 2.]
[ 0. 1. 5.]
[ 0. 1. 8.]
[ 0. 1. 11.]
[ 0. 1. 14.]
[ 0. 1. 17.]
[ 0. 4. 2.]
[ 0. 4. 5.]
I'm not really sure how you think your code was supposed to work. You are appending a row in X at each loop, so 3 * 3 * 7 times, so you end up with a matrix of 54 x 3.
I think maybe you meant to do:
for i in range(3):
X = np.append(X, [[3*i , 3*i+1, 3*i+2]], axis=0)
Just so you know, appending array is usually discouraged (just create a list of list, then make it a numpy array).
You could also do
>> np.arange(9).reshape((3,3))
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])

I am trying to solve 0/1 Knapsack problem, but I am getting output as many zeroes

Below is the code given for 0/1 knapsack problem, where i am getting most zeroes in my output table. How can I understand why this problem is happening and how to solve this issue?
item = 4
profit = [1, 2, 4, 5]
weight = [5, 4, 8, 6]
bag = 5
import numpy as np
table=np.zeros([item,bag])
for j in range(bag):
for i in range(len(weight)):
if i==0 or j==0 :continue
elif j< weight[i]:
table[i][j] = table[i-1][j]
#print(i,j)
else:
table[i][j] =max((profit[i]+table[i-1][j-weight[i]]),
(table[i-1][j]))
print(table)
The output I am getting is:
[[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 2.]
[ 0. 0. 0. 0. 2.]
[ 0. 0. 0. 0. 2.]]

Numpy broadcasting of fancy index

How does the np.newaxis work within the index of numpy array in program 1? Why it works like this?
Program 1:
import numpy as np
x_id = np.array([0, 3])[:, np.newaxis]
y_id = np.array([1, 3, 4, 7])
A = np.zeros((6,8))
A[x_id, y_id] += 1
print(A)
Result 1:
[[ 0. 1. 0. 1. 1. 0. 0. 1.]
[ 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 1. 0. 1. 1. 0. 0. 1.]
[ 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0.]]
The newaxis turns the x_id array into a column vector, same as np.array([[0],[3]]).
So you are indexing A at the cartesian product of [0,3] and [1,3,4,7]. Or to put it another way, you end up with 1s for rows 0 and 3, columns 1,3,4,and 7.
Also look at np.ix_([0,3], [1,3,4,7])
or
In [832]: np.stack(np.meshgrid([0,3],[1,3,4,7],indexing='ij'),axis=2)
Out[832]:
array([[[0, 1],
[0, 3],
[0, 4],
[0, 7]],
[[3, 1],
[3, 3],
[3, 4],
[3, 7]]])
Be a little careful with the +=1 setting; if indices are duplicated you might not get what you expect, or would get with a loop.

How to initialise a Numpy array of numpy arrays

I have a numpy array D of dimensions 4x4
I want a new numpy array based on an user defined value v
If v=2, the new numpy array should be [D D].
If v=3, the new numpy array should be [D D D]
How do i initialise such a numpy array as numpy.zeros(v) dont allow me to place arrays as elements?
If I understand correctly, you want to take a 2D array and tile it v times in the first dimension? You can use np.repeat:
# a 2D array
D = np.arange(4).reshape(2, 2)
print D
# [[0 1]
# [2 3]]
# tile it 3 times in the first dimension
x = np.repeat(D[None, :], 3, axis=0)
print x.shape
# (3, 2, 2)
print x
# [[[0 1]
# [2 3]]
# [[0 1]
# [2 3]]
# [[0 1]
# [2 3]]]
If you wanted the output to be kept two-dimensional, i.e. (6, 2), you could omit the [None, :] indexing (see this page for more info on numpy's broadcasting rules).
print np.repeat(D, 3, axis=0)
# [[0 1]
# [0 1]
# [0 1]
# [2 3]
# [2 3]
# [2 3]]
Another alternative is np.tile, which behaves slightly differently in that it will always tile over the last dimension:
print np.tile(D, 3)
# [[0, 1, 0, 1, 0, 1],
# [2, 3, 2, 3, 2, 3]])
You can do that as follows:
import numpy as np
v = 3
x = np.array([np.zeros((4,4)) for _ in range(v)])
>>> print x
[[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]]
Here you go, see if this works for you.
import numpy as np
v = raw_input('Enter: ')
To intialize the numpy array of arrays from user input (obviously can be whatever shape you're wanting here):
b = np.zeros(shape=(int(v),int(v)))
I know this isn't initializing a numpy array but since you mentioned wanting an array of [D D] if v was 2 for example, just thought I'd throw this in as another option as well.
new_array = []
for x in range(0, int(v)):
new_array.append(D)

Categories