I am creating the list as follows:
myList = []
for i in range(0,10):
val0 = 1 # some formula for obtaining values
val1 = 2.5
val2 = 1.8
myList.append([val0,val1,val2])
How can I do the same loop for pandas DataFrame (i.e. myList
must be a DataFrame
).
Since a DataFrame is similar to a 2D Numpy array, we can create one from a Numpy ndarray . You should remember that the input Numpy array must be 2D, otherwise you will get a ValueError. If you pass a raw Numpy ndarray , the index and column names start at 0 by default.
In Python, there is not C like syntax for(i=0; i<n; i++) but you use for in n . They can be used to iterate over a sequence of a list , string , tuple , set , array , data frame . Given a list of elements, for loop can be used to iterate over each item in that list and execute it.
Ideally you want to create your DataFrame
once you have all the data in place. Slightly modifying your example:
my_df = []
for i in range(0,10):
d = {
'val0' : 1, # some formula for obtaining values
'val1' : 2.5,
'val2' : 1.8
}
my_df.append(d)
my_df = pd.DataFrame(my_df)
So now my_df
is a DataFrame
with val0
, val1
and val2
as columns
if i got your question right:
import pandas as pd
myList = []
for i in range(0,10):
val0 = 1 # some formula for obtaining values
val1 = 2.5
val2 = 1.8
myList.append([val0,val1,val2])
df = pd.DataFrame(myList, columns=['val0','val1','val2'])
print(df)
PS you don't want to do append data to the DataFrame in the loop - it won't be very efficient.
Output:
val0 val1 val2
0 1 2.5 1.8
1 1 2.5 1.8
2 1 2.5 1.8
3 1 2.5 1.8
4 1 2.5 1.8
5 1 2.5 1.8
6 1 2.5 1.8
7 1 2.5 1.8
8 1 2.5 1.8
9 1 2.5 1.8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With