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?

3 Answers 3

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 
Sign up to request clarification or add additional context in comments.

2 Comments

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.
are you using same value d = {'a':'1,2,3','b':'3,4,5,6'} ?
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 

2 Comments

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.
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.
0

Hope this helps:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.