Iterate through list items and convert items to pandas df using with forloop in python

Viewed 169

I have a huge list of tweets generated by Tweepy. I need to go through each item of the list and convert it to pd Df, for example:

df_1=pd.DataFrame(data[0][0])
df_2=pd.DataFrame(data[1][0])
df_3=pd.DataFrame(data[2][0])

I would like to create a for loop to do this automatically. I've tried this but it is not working for me. Would anyone know?

for i in range(120):
    dataframe_from_each_list_element = pd.DataFrame(data[i][0])
    for dataframe in dataframe_from_each_list_element:
        appended_dataframe.append(pd.Series(dataframe), ignore_index=True)

Many thanks

1 Answers

The simplest to match you original example is to use a loop

As list comprehension:

dfs = [pd.DataFrame(subdata[0]) for subdata in data]

As classical for loop:

dfs = []

for subdata in data:
    dfs.append(pd.DataFrame(subdata[0]))

You will have a list of DataFrames that you can index per position:

# 12th dataframe
dfs[11]
Related