0

I have a problem and I was hoping you can help me. So I'm writing a code to calculate the shortest path length using networkx and numpy, so I create a function to do this,

def costos(red, precios):
    pathlength = []

    for i in redes: #3d array with 100 2D arrays 
        graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
        pathlength.append(nx.shortest_path_length(graph, 0, 1, weight = 'weight'))
        y = np.array(pathlenght)
        z = np.shape(y)

    return y, z

and when I print the result I got the next output

[25, 10, 32, ..., 20] #A 1D array with 100 elements (shortest path length)
(100,) #Shape of the 1D array

What I want is to transform this 1D array with size of (100,) to a 2D array of size (10, 10), I know I can use np.reshape but when I add this to my function like this

for i in redes: #3d array with 100 arrays
    graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
    pathlength.append(nx.shortest_path_length(graph, 0, 1, weight = 'weight'))
    y = np.array(pathlenght)
    z = np.shape(y)
    w = np.reshape(y, (10,10))

I get the next Value Error

cannot reshape array of size 1 into shape (10,10)

What I'm doing wrong? I tried different things but nothing seems to work, so any help will be appreciated, thank you!

3
  • 1
    pathlength is probably a list of arrays. Which cannot be reshaped Commented Mar 19, 2020 at 18:07
  • 1
    Pay closer attention to the indents. You accumulate values in pathlenght, and (100,) shape y is the result of the last loop (the previous y values are thrown away). In the 2nd case you try to reshape before y contains all 100 samples. All of the y,z,w code should be outside of the for loop. Commented Mar 19, 2020 at 19:55
  • @hpaulj I see, yeah, it work now! thank you! Commented Mar 20, 2020 at 11:47

1 Answer 1

1

Because of the fact, that I can't duplicate your error. I created my own output: import numpy as np

arr = np.arange(100)
print(arr.shape)
print(arr.dtype)

which return the size of: (100,) int64

And when I now use np.reshape, it works like that.

print(arr.reshape((10, 10)))

with the following output:

[[ 0  1  2  3  4  5  6  7  8  9]
[10 11 12 13 14 15 16 17 18 19]
[20 21 22 23 24 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]]

If that example doesn't help, please specify an example to replicate or at least specify the dtype of the array and the type of the produced data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.