Home > database >  How can I save a new array in iteration in a loop
How can I save a new array in iteration in a loop

Time:11-12

Let me preface this by saying that I am new to programming. I would like to create a new array for each iteration, not add elements to the same array. How can I create a new array?

If I use E=np.array[(...)]

in my loop, I will be rewriting the array every singe time. I want to have a series of arrays saved so that I can Add them to a data frame later and then sort the arrays by the size of the first element.

Here is my code:


E=0
n=0
En=np.array(0)
for x in range(1,7):
    for y in range(1,7):
        for z in range(1,7):
            E= x**2 y**2 z**2
            if E<=14:
                n= n 1
                print( "the energy and the nx, ny, nz is", E,x, y, z)
              E=
            if E> 14:
                    break
                       
print(f'there are {n} cobinations')  
                

I actually don't know. I am new to programming and could not find any answers to "create a new array in the loop", and I did try this:

for x in range(1,7):
    for y in range(1,7):
        for z in range(1,7):
            E= x**2 y**2 z**2
            if E<=14:
                n= n 1
                print( "the energy and the nx, ny, nz is", E,x, y, z)
                Exyz=np.array([E,x,y,z])
            if E> 14:

This does not allow me to create a new array corresponding to each loop.

CodePudding user response:

you can use an empty list and after that in every iterate append new list to that (if you like to have array, change the list to np.array in last line of code)

import numpy as np

E = 0
n = 0
# define empty list
En = []

for x in range(1, 7):
    for y in range(1, 7):
        for z in range(1, 7):
            E = x ** 2   y ** 2   z ** 2
            if E <= 14:
                n = n   1
                print("the energy and the nx, ny, nz is", E, x, y, z)
                # append new list to En list
                En.append([E, x, y, z])
            if E > 14:
                break

print(f'there are {n} cobinations')
# if you like to have array,
En = np.array(En)
print(En)

CodePudding user response:

Based on your statement "I want to have a series of arrays saved so that I can Add them to a data frame later" I suggest that you initiate an empty dataframe and then append each loop's resulting array to the dataframe with an appropriate unique ID identifying the loop it came from.

df=pd.DataFrame() 
E=0
n=0
En=np.array(0)
for x in range(1,7):
    for y in range(1,7):
        for z in range(1,7):
            E= x**2 y**2 z**2
            if E<=14:
                n= n 1
                df=df.append(pd.DataFrame([[E,x,y,z]],columns=['E','x','y','z']))
                Exyz=np.array([E,x,y,z])
            if E> 14:
                break
  • Related