Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through a list of pandas DataFrames and perform operations

Tags:

python

pandas

This is a basic question, but I want to loop through a list of DataFrames and for each DataFrame, set the index as one of the columns in the DataFrame.
The issue with the code below is that it doesn't save the DataFrame with a new index. How do I format this For loop so that the DataFrames are permanently changed outside of the for loop? Thanks.

dflist = [df_1, df_2, df_3]

for df in dflist:
    df = df.set_index('column_2')
like image 383
geeb.24 Avatar asked Oct 23 '25 09:10

geeb.24


2 Answers

As you have probably guessed, i is just a temporary value. Use i as only an index using enumerate

for i, df in enumerate(dflist):
    dflist[i] = dflist[i].set_index('column_2'))
like image 162
Oasa Avatar answered Oct 26 '25 06:10

Oasa


for i in dflist:
    i.set_index('column_2', inplace=True)
like image 32
Love Tätting Avatar answered Oct 26 '25 04:10

Love Tätting