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?
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?
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)
reset_index is not an inplace operation.df = df.reset_index() instead of dataframe.reset_index(inplace=True), it won't work...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]
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)
reset_index is not an inplace operation.