2

How to reset index of multiple pandas dataframes using a loop in python?

I have 17 dataframes in a list and I want to reset index for all of them using a loop.

Any help?

3
  • 1
    in what structure you have multiple df eg.in list etc Commented Apr 8, 2019 at 17:31
  • Please show us some code so we can help you achieve what you seek Commented Apr 8, 2019 at 17:32
  • Yes, my dfs are in a list Commented Apr 8, 2019 at 17:34

3 Answers 3

3

This would be the simplest way imo:

#This list contains the names of all of your dataframes
list_dataframes = [foo1, foo2, foo3, ..... , foo17]

for dataframe in list_dataframes:
    dataframe.reset_index(inplace=True)
Sign up to request clarification or add additional context in comments.

2 Comments

This will not change the dataframes in list_dataframes because reset_index is not an inplace operation.
Can't understand why if I use df = df.reset_index() instead of dataframe.reset_index(inplace=True), it won't work...
2

You need to remember that reset_index is not an inplace operation and you need to reassign or use the inplace parameter.

df1 = pd.DataFrame(index=np.arange(1,10))
df2 = pd.DataFrame(index=pd.date_range('2019-01-1', periods=10))
df3 = pd.DataFrame(index=[*'ABCDEFGHIJ'])

lofdfs = [df1, df2, df3]
for df in lofdfs:
    df.reset_index(inplace=True)

Or, use list comprehension:

[df.reset_index(inplace=True) for df in lofdfs]

Comments

1

Pandas's documentation say:

reset_index: Reset the index of the DataFrame, and use the default one instead. If the DataFrame has a MultiIndex, this method can remove one or more levels.

This is util when you has complex dataframe, but if you has separate dataframes you can do like:

for df in dataframes:
    df.reset_index(inplace=True)

1 Comment

This will not change the df in dataframes, because reset_index is not an inplace operation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.