Home > OS >  Convert a list to dataframe using for loop
Convert a list to dataframe using for loop

Time:10-10

from itertools import chain
data_c = chain(data[0].values,
data[1].values,
data[2].values,
data[3].values,
data[4].values,
data[5].values,
data[6].values)

headers=chain(data[0])
df = pd.DataFrame(data_c, columns=headers)

I have used the above code lines to convert a list to a pd dataframe and it works fine. The result looks like this.all 178 rows displayed

However, i want to loop through all the list data so I have used the following codes:

from itertools import chain
import pandas as pd
for i in range (0, len(data)):
    data_c = chain(data[i].values)

headers=chain(data[0])
df = pd.DataFrame(data_c,columns=headers)

The result only shows the last value (which is the data[6].values).Only 8 rows are displayed Anyone knows how to fix this?

CodePudding user response:


for i in range (0, len(data)):
    data_c = chain(data[i].values)
    # Here every time loop runs data_c values override to a new chain object, That's why the data_c value in set to the last value.

Try this.

from itertools import chain
import pandas as pd

data_c = chain(*[ele.values for ele in data]) 

headers=chain(data[0])
df = pd.DataFrame(data_c,columns=headers)

CodePudding user response:

Probably you need to append data in the loop for every iteration of data;

data_c = pd.DataFrame()
for i in range (0, len(data)):
    data_c = pd.concat[data_c,chain(data[i].values)]
  • Related