1

I have a dictionary like the below

d = {'a':'1,2,3','b':'3,4,5,6'}

I want to create dataframes from it in a loop, such as

a = 1,2,3
b = 3,4,5,6

Creating a single dataframe that can reference dictionary keys such as df['a'] does not work for what I am trying to achieve. Any suggestions?

Artem
  • 29
  • 1
  • 2

3 Answers3

1

Try this to get a list of dataframes:

>>> import pandas as pd
>>> import numpy as np
>>> dfs = [pd.DataFrame(np.array(b.split(',')), columns=list(a)) for a,b in d.items()]

gives the following output

>>> dfs[0]
   a
0  1
1  2
2  3
>>> dfs[1]
   b
0  3
1  4
2  5
3  6
abhilb
  • 5,639
  • 2
  • 20
  • 26
  • Thanks for your reply! Getting this error: 'list' object has no attribute 'split'. I should have specified that I have a nested dictionary, I assume that's where the issue is coming from. – Artem Nov 26 '19 at 20:34
  • are you using same value `d = {'a':'1,2,3','b':'3,4,5,6'}` ? – abhilb Nov 26 '19 at 21:11
0

To convert your dictionary into a list of DataFrames, run:

lst = [ pd.Series(v.split(','), name=k).to_frame()
    for k, v in d.items() ]

Then, for your sample data, lst[0] contains:

   a
0  1
1  2
2  3

and lst[1]:

   b
0  3
1  4
2  5
3  6
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
  • Thanks for your reply! Getting this error: 'list' object has no attribute 'split'. I should have specified that I have a nested dictionary, I assume that's where the issue is coming from. – Artem Nov 26 '19 at 20:34
  • The fact that you have **nested** dictionary changes a lot. My answer was prepared with "simple" dictionaries in mind. The mutation of your original task is actually a good material for **another** question, not for extending your original question. – Valdi_Bo Nov 26 '19 at 21:01
0

Hope this helps:

dfs=[]  
for key, value in d.items():  
    df = pd.DataFrame.from_dict((list(filter(None, value)))) 
    dfs.append(df)