noob
noob

Reputation: 3811

Convert list to dataframe by adding list values to df within for loop pandas

I have a simple list

Code to retrieve i, v list:

 for i, v in enumerate(list_name_1):
    print(i, v)

Output

    5 -100
    4 30
    0 -90
    1 -80
    3 100
    2 1000
    and so on

I wish to store all these in a dataframe.

The problem is I am doing lot of calculations on list_name_1 within the for loop, hence I need to catch i and v values in the for loop only. So I cant do a simple df=pd.DataFrame(list_name_1) for e.g.

I will need to do something like below:

df = []
 for i, v in enumerate(list_name_1):
        print(i, v)
        some code to add i,v iteratively in columns i and v of df

Upvotes: 1

Views: 2453

Answers (3)

Evandro Lippert
Evandro Lippert

Reputation: 366

I think you can do that:

for i, v in enumerate(list_name_1):
    diction = {'i': i, 'v': v}
    df = df.append(diction, ignore_index=True)
    

I don't know how you are doing the calculation, but I think it is a good way to catch all values.

Upvotes: 1

OmkarKhilari
OmkarKhilari

Reputation: 62

I think you should use predifined syntax for this.Using for loops is really long way.

import pandas as pd

L = ["This","Is","A","List"]
M = ["This","Is","Also","List"]
#create new dataframe
df = pd.DataFrame({'col':L,'col2':M})
print (df)


           col  col2
       0  This  This
       1    Is    Is
       2     A  Also
       3  List  List

Upvotes: -2

Marcus
Marcus

Reputation: 1023

An idea is to create two lists, one which stores the calculated values of i, and one for v. So:

i_values = []
v_values = []
for i, v in enumerate(list_name_1):
    print(i, v)
    # Make calculations for i and v
    i_values.extend([calculated_i])
    v_values.extend([calculated_v])

df = pd.DataFrame(data={"i": i_values, "v": v_values})

Upvotes: 2

Related Questions