-1

Tried a lot but I'm not able to cast the whole elements into array,I want 10 elements in my 1D Array

I Use This Code

    import numpy as np
    list1=np.random.randint(low=50,high=100,size=50).reshape(10,5)
    for i in list1.flat:
        print(i)
    list2=np.array(i,dtype=int)
    list2

To See The Output >>>>>> Refer To this pic

I'm always getting 1 element as output instead of 10 elements

Please Suggest Only Modification Into This Code

Community
  • 1
  • 1
  • It is unclear, what you are asking for. Do you want create a 1D copy of the array? You have to provide context, what you are trying to achieve. – Mr. T Jan 30 '18 at 17:55
  • I think,You don't go through the entire code.Please Go through the code and then down vote,it impacts the profile – Amarjeet Ranasingh Jan 30 '18 at 18:00
  • 1
    I've read your code and according to it, you want to create a numpy array from the last element of another array. Obviously not, what you want to achieve. So you should describe clearly, what the expected output is with a [verifiabel example](https://stackoverflow.com/help/mcve). We only see, what you write in your question. – Mr. T Jan 30 '18 at 18:06
  • I agree with @Piinthesky that it is not clear what you want to achieve – AGN Gazer Jan 30 '18 at 22:29
  • Please Check,is it specific right now? – Amarjeet Ranasingh Jan 31 '18 at 12:21

3 Answers3

0

I'm assuming since you know about np.reshape you have some reason to need to use a loop?

Assuming that's true, you can instantiate list2 outside of the loop and then append values inside the loop. Right now you are making a new np array every time you go through the loop, hence on leaving the loop you simply have a new np array with the final value.

I.e.

list2 = np.array(np.zeros(50))
j = 0 
for i in list1.flat:
    list2[j] =  i
    j+=1
0

I have to agree with @Piinthesky that your problem is not well formulated. I suspect (but I am not sure) that you want to obtain a flattened (1D) version of the 2D array list1. Please refer to https://stackoverflow.com/a/28930580/8033585 for more details on differences between ravel, reshape, and flatten.

Thus, you can get a flattened array as:

Method 1:

list2 = list1.reshape(-1) # returns a view! modifying list2 modifies list1

Method 2:

list2 = list1.ravel() # returns a view most of the time (unless list1 is not contiguous)!

Method 3:

list2 = list1.flatten() # returns a 1D **copy** of list1
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
0

Since your question is not clear i assumed you have given reshape(10,5) that will caste data always in 5 columns if i understood right. try this:-

import numpy as np
list1=np.random.randint(low=50,high=100,size=50).reshape(5,10)
for i in list1:
  print (i)
Narendra
  • 1,511
  • 1
  • 10
  • 20