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?
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.
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.
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.
You can convert a dictionary to Pandas Dataframe using df = pd. DataFrame. from_dict(my_dict) statement.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With