0

I search the forum and see that it's possible to assign a list to a df cell, but can you assign one df to a df cell (i.e. nest dataframe to dataframe?)

    A              B                     C   
0  Rep1   df_sales1(dataframe)  df_bonus1(dataframe)
1  Rep2   df_sales2(dataframe)  df_bonus2(dataframe)

Based on @ Mohamed Thasin ah below, I tried the following;

df1 = pd.DataFrame(np.random.randint(1,10, size = (3,3)), columns = ['A','B','C'])
df2 = pd.DataFrame(np.random.randint(1,10, size = (3,3)), columns = ['A','B','C'])
df3 = pd.DataFrame(np.random.randint(1,10, size = (3,3)), columns = ['A','B','C'])
dfs = pd.DataFrame({'idx': [0,1,2], 'dfs':[df1, df2, df3]})

dfs
   idx              dfs
0   0   A B C 0 3 4 6 1 3 5 5 2 6 2 5
1   1   A B C 0 2 9 9 1 6 5 5 2 9 1 1
2   2   A B C 0 3 7 2 1 8 5 1 2 9 4 8

Now I create another df_extra,

df_extra = pd.DataFrame(np.random.randint(10,100, size= (2,2)), columns = ['extra1', 'extra2'])
df_extra

  extra1  extra2
0   60      86
1   97      75

Now I tried to add another column in the original df, and add the df_extra to that column, say in the second row. This is where I run into problems. I tried different method to add this df_extra as list as follows;

dfs.loc[1,'extra'] = [df_extra]

this creates error:

......
ValueError: setting an array element with a sequence.

How should I do that to get the following:

   idx              dfs                   extra
0   0   A B C 0 3 4 6 1 3 5 5 2 6 2 5      NaN
1   1   A B C 0 2 9 9 1 6 5 5 2 9 1 1    **[df_extra]**  
2   2   A B C 0 3 7 2 1 8 5 1 2 9 4 8      NaN
  • You can keep dfs in to list and access based on the requirement. Any reason why you want to use dataframe to store dataframes? – Mohamed Thasin ah Aug 04 '22 at 10:02
  • I have quite many dfs so I'm trying to consolidate them by setting up nested data structure for easy management. Based on your recommendation I did some trial but still couldn't get the assignment work properly. I will add to the question of what I have tried. – Michael Ling Aug 05 '22 at 09:06

0 Answers0