Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas dataframe from dictionary of list values

I have a dictionary with lists as values such as:

cols = {'animals':['dog','cat','fish'],
        'colors':['red','black','blue','dog']}

I want to convert this into a dataframe in which each of the lists are enumerated according to their key with the result of

key variable
animals dog
animals cat
animal fish
colors red
colors black
colors blue
colors dog

SO far, I have done this: but it does not provide me with desired result.

cols_df = pd.DataFrame.from_dict(cols, orient='index')

How can I modify this to achieve the above?

like image 590
owwoow14 Avatar asked Jun 07 '18 22:06

owwoow14


People also ask

Can we create DataFrame from dictionary of lists?

Creating pandas data-frame from lists using dictionary can be achieved in multiple ways. Let's discuss different ways to create a DataFrame one by one. With this method in Pandas, we can transform a dictionary of lists into a dataframe.

Can we create DataFrame from list and dictionary in Python?

We can create a pandas DataFrame object by using the python list of dictionaries. If we use a dictionary as data to the DataFrame function then we no need to specify the column names explicitly. Here we will create a DataFrame using a list of dictionaries, in the below example.

When we create DataFrame from dictionary of list then list becomes?

On Initialising a DataFrame object with this kind of dictionary, each item (Key / Value pair) in dictionary will be converted to one column i.e. key will become Column Name and list in the value field will be the column data i.e.

How do I convert a dictionary to a DataFrame in Pandas?

You can convert a dictionary to Pandas Dataframe using df = pd. DataFrame. from_dict(my_dict) statement.


1 Answers

No imports, works on all inputs:

>>> pd.DataFrame([(key, var) for (key, L) in cols.items() for var in L], 
                 columns=['key', 'variable'])

       key variable
0  animals      dog
1  animals      cat
2  animals     fish
3   colors      red
4   colors    black
5   colors     blue
6   colors      dog
like image 127
BallpointBen Avatar answered Sep 21 '22 01:09

BallpointBen