Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Python DataFrame from dictionary where keys are the column names and values form the row

Tags:

I am familiar with python but new to panda DataFrames. I have a dictionary like this:

a={'b':100,'c':300}

And I would like to convert it to a DataFrame, where b and c are the column names, and the first row is 100,300 (100 is underneath b and 300 is underneath c). I would like a solution that can be generalized to a much longer dictionary, with many more items. Thank you!

like image 946
user3433489 Avatar asked Aug 14 '14 22:08

user3433489


People also ask

How will you create a data frame from dictionary with key values as rows?

Method 1: Create DataFrame from Dictionary using default Constructor of pandas. Dataframe class. Method 2: Create DataFrame from Dictionary with user-defined indexes. Method 3: Create DataFrame from simple dictionary i.e dictionary with key and simple value like integer or string value.

When constructing a DataFrame from a dictionary How are the keys in the dictionary used?

from_dict() function. By default, it creates a dataframe with the keys of the dictionary as column names and their respective array-like values as the column values. If you want the dictionary keys to be row indexes instead, pass 'index' to the orient parameter (which is 'columns' by default).

How convert dictionary to DataFrame in python with keys as columns?

Convert Dictionary To Dataframe With Keys As Columns You can do this by using the orient = 'columns' parameter in the from_dict() method as demonstrated below. This is the default behavior of the from_dict() method. What is this? The dataframe is created with the dictionary keys as rows as shown below.

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

We can convert a dictionary to a pandas dataframe by using the pd. DataFrame. from_dict() class-method.


1 Answers

Pass the values as a list:

a={'b':[100,],'c':[300,]}
pd.DataFrame(a)

     b    c
0  100  300

Or if for some reason you don't want to use a list, include an index:

a={'b':100,'c':300}
pd.DataFrame(a, index=['i',])

     b    c
i  100  300
like image 168
iayork Avatar answered Sep 17 '22 03:09

iayork