CRoNiC
CRoNiC

Reputation: 409

How to store a Dataframe in a Dictionary

I have a Dataframe that extends column-wise by using a for-loop. now I want to store certain "stages" of the evolving DF somehow and I thought it would be the best to use a Dictionary.

to give you a picture:

df_dict={}
for i in range(1,13):
    df=pd.read_csv('./test.csv').iloc[:,0:i*4-1]

so I want to store this as "first stage" of the df:

col1     col2     col3     col4
  1        3        5        7
  2        4        6        8

in the "second stage":

col1     col2     col3     col4     col5     col6     col7     col8
  1        3        5        7        9        11       13       15
  2        4        6        8        10       12       14       16    

3rd stage contains 12 cols:

col1     col2     col3     col4     col5     col6     col7     col8     ...
  1        3        5        7        9        11       13       15     ...
  2        4        6        8        10       12       14       16     ...

Ongoing till the 12th stage contains 48 cols.

So in general I want to store in the Dict these stages where every new stage has 4 more columns. And I need to be able to use these different Dataframes seperatly later.

I know that

df_dict.update({i, df})

doesn't work since DFs are mutable, but I did not manage to find a way to work around it.

I'm new to Python so please by gentle with me. Cheers!

EDIT: I wasn't searching the Idea of how to get variable variables since I allready mentioned that I want to use a Dict, but I was looking for a way of storing my Dataframe in a Dict.

Upvotes: 6

Views: 23366

Answers (1)

jezrael
jezrael

Reputation: 863801

I believe you need to assign each DataFrame in loop:

df_dict={}
for i in range(1,13):
    df=pd.read_csv('./test.csv').iloc[:,0:i*4-1]
    df_dict[i] = df

Another solution is use dictionary comprehension:

df_dict = {i: pd.read_csv('./test.csv').iloc[:,0:i*4-1] for i in range(1,13)}

Upvotes: 6

Related Questions