How to dynamically name dataframes?

Question:

Suppose I have a dataframe as follows:

s = df.head().to_dict()
print(s)

{'BoP transfers': {1998: 12.346282212735618,
  1999: 19.06438060024298,
  2000: 18.24888031473687,
  2001: 24.860019912667006,
  2002: 32.38242225822908},
 'Current balance': {1998: -6.7953,
  1999: -2.9895,
  2000: -3.9694,
  2001: 1.1716,
  2002: 5.7433},
 'Domestic demand': {1998: 106.8610389799729,
  1999: 104.70302507466538,
  2000: 104.59254229534136,
  2001: 103.83532232336977,
  2002: 102.81709401489702},
 'Effective exchange rate': {1998: 88.134,
  1999: 95.6425,
  2000: 99.927725,
  2001: 101.92745,
  2002: 107.85565},
 'RoR (foreign liabilities)': {1998: 0.0433,
  1999: 0.0437,
  2000: 0.0542,
  2001: 0.0539,
  2002: 0.0474},
 'Gross foreign assets': {1998: 19.720897432405103,
  1999: 22.66200738564236,
  2000: 25.18270679890144,
  2001: 30.394226651732836,
  2002: 37.26477320359688},
 'Gross domestic income': {1998: 104.9037939043707,
  1999: 103.15361867816479,
  2000: 103.06777792080423,
  2001: 102.85886528974339,
  2002: 102.28518242008846},
 'Gross foreign liabilities': {1998: 60.59784839338306,
  1999: 61.03308220978983,
  2000: 64.01438055825233,
  2001: 67.07798172469921,
  2002: 70.16108592109364},
 'Inflation rate': {1998: 52.6613,
  1999: 19.3349,
  2000: 16.0798,
  2001: 15.076,
  2002: 17.236},
 'Credit': {1998: 0.20269913592846378,
  1999: 0.2154280880177353,
  2000: 0.282948948505006,
  2001: 0.3954812893893278,
  2002: 0.3578263032373988}}

which can be converted back to its original form using:

df = pd.DataFrame.from_dict(s)

I am interested in dynamically naming dataframes such that, for instance:

dim = df.shape[1]

counter1 = 0
counter2 = 1

while(counter1 <= dim):
   df_str(counter2) = df.iloc[:, counter1: (counter1 + 3)]
   counter1 = counter1 + 3
   counter2 = counter2 + 1

Obviously this code is wrong and won’t work. But essentially I need to end up with df_1, df_2, df_3 and so on, depending on the number of columns of the dataframe. I have read in many posts that this is bad practice and that this can be accomplished using dictionaries; but this is not clear to me. Some guidance is very much appreciated.

Asked By: Carl

||

Answers:

i = 0
res = []
while i < df.shape[1]:
    res.append(df.iloc[:, i: (i + 3)])
    i = i + 3
print(res[0])
print(res[1])
print(res[2])
Answered By: Ricardo
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.