Skip to content Skip to sidebar Skip to footer

Populating New List When Each Element Is An Array

I'm trying to create a new list of data from some existing data. Currently though I am having the problem where each element of my new list is being saved as its own single-element

Solution 1:

I do not have the data but this might work:

old_data = np.reshape(old_data, (49210, 1)) #Reshape into 1D arraythreshold = np.nanmax(old_data) #Create threshold to be used as condition for new new_data = [element for element in old_data if element > threshold]

List comprehension is both faster and much prettier to use instead of for loops with append.

In case you have ended up with a array of arrays you might want to try the following instead:

old_data = np.reshape(old_data, (49210, 1)) #Reshape into 1D arraythreshold = np.nanmax(old_data) #Create threshold to be used as condition for new new_data = [element[0] for element in old_data if element[0] > threshold]

Solution 2:

So I see, you are using numpy library to flatten a 2D array to a 1D array.

What you can do is flatten your 2D array into a 1D array and then append your old list to your new list as you would like.

To flatten a 2D array to a 1D array -

import numpy as np 
  
ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]]) 
   
# Multiplying arrays 
result = ini_array1.flatten() 
  
# printing result 
print("New resulting array: ", result) 

The result will be your old 2D array as a normal 1D array or a python list which you can append to your new list to get your final list.

Solution 3:

Thank you both @JakobVinkas and @Innomight. I've tried both solutions and both have worked. I'm still slightly confused as to why I was originally getting this problem but I will just read up on that I guess.

For anyone who may have come across this question later I have implemented what Jakob suggested using element[0] as my solution.

Also I have found this question and this question to be a good explanation of what is fundamentally happening here in the first place.

Post a Comment for "Populating New List When Each Element Is An Array"