How to read multiple pandas dataframes simultaneously using loop?

Question:

I am trying to simultaneously read every record of multiple dataframes in pandas and I have created a list of these dataframes but how to read every record simultaneously?

import pandas as pd
import numpy as np
df1 = pd.DataFrame({'a':np.arange(4), 'b':np.arange(4)})


df1

    a   b
0   0   0
1   1   1
2   2   2
3   3   3

df2 = pd.DataFrame({'a':np.arange(4), 'b':np.arange(4)})
df2

    a   b
0   0   0
1   1   1
2   2   2
3   3   3

df3 = pd.DataFrame({'a':np.arange(4), 'b':np.arange(4)})
df3

    a   b
0   0   0
1   1   1
2   2   2
3   3   3

I want to change the headers of these groups of dataframes simultaneuosly with the name of the dataframes like

df1:

    df1a    df1b
0   0        0
1   1        1
2   2        2
3   3        3


df2:

    df2a    df2b
0   0        0
1   1        1
2   2        2
3   3        3


df3:

df1:

    df3a    df3b
0   0        0
1   1        1
2   2        2
3   3        3

I have a list of all the dataframes like lst1=[df1,df2,df3......].

Can someone help?

Asked By: rjk

||

Answers:

According to me you can do it as follows:

Create a array of all data frames and then loop through them as follows. This will dynamically rename headers according to there index position.

allDf = [df1, df2, df3]
    
for i,j in enumerate(allDf):
   allDf[I] = j.add_prefix("df"+str(i+1))

And you will get the desired output as:

df1:

    df1a    df1b
0   0        0
1   1        1
2   2        2
3   3        3


df2:

    df2a    df2b
0   0        0
1   1        1
2   2        2
3   3        3


df3:

    df3a    df3b
0   0        0
1   1        1
2   2        2
3   3        3
Answered By: Akash
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.