Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Dictionary from a Dataframe With the Index as the Keys

Tags:

python

pandas

df.to_dict() creates a nested dictionary where the headers form the keys, {column:{index:value}}.

Is there an easy way to create a dictionary where the index forms the keys, {index:column:value}}? Or even {index:(column,value)}?

I can create the dictionary and then invert it, but I was wondering if this can be done in a single step.

like image 934
Batman Avatar asked Aug 22 '14 16:08

Batman


People also ask

How do I convert a Pandas DataFrame to a dictionary?

Use DataFrame. To convert pandas DataFrame to Dictionary object, use to_dict() method, this takes orient as dict by default which returns the DataFrame in format {column -> {index -> value}} . When no orient is specified, to_dict() returns in this format.

Can I use index for dictionary Python?

Python dictionary index of key By using list(*args) with a dictionary it will return a collection of the keys. We can easily use the index to access the required key from the method and convert it to a list. In this example to use the list[index] function and it will return the key at index in the list.

Can you index into a dictionary?

You can find a dict index by counting into the dict. keys() with a loop. If you use the enumerate() function, it will generate the index values automatically.

How to return a dictionary with Dataframe indexes as keys?

Now, instead of columns, if you want the returned dictionary to have the dataframe indexes as keys, pass 'index' to the orient parameter. The returned dictionary has the format {index: {column: value}}

How to create a pandas Dataframe from a dictionary?

In this tutorial, we’ll look at how to create a pandas dataframe from a dictionary with some examples. The pandas.DataFrame.from_dict () function is used to create a dataframe from a dict object. The dictionary should be of the form {field: array-like} or {field: dict}.

How to create a Dataframe with row index?

It takes 'columns' or 'index' and is 'columns' by default. If the keys in your dictionary represent row indexes then pass orient='index' The created dataframe has keys as row indexes. You can also pass the column names as a list to the columns parameter when creating a dataframe with orient='index'

How to create a Dataframe from a dict object in Python?

The pandas.DataFrame.from_dict () function The pandas.DataFrame.from_dict () function is used to create a dataframe from a dict object. The dictionary should be of the form {field: array-like} or {field: dict}. The following is its syntax:


Video Answer


1 Answers

Transpose the dataframe before you use df.to_dict.

df = pd.DataFrame({'a': [1, 3, 5], 'b': [2, 7, 5]})

print(df)
#    a  b
# 0  1  2
# 1  3  7
# 2  5  5

print(df.transpose().to_dict())
# {0: {'a': 1, 'b': 2}, 
#  1: {'a': 3, 'b': 7}, 
#  2: {'a': 5, 'b': 5}}
like image 192
Roger Fan Avatar answered Sep 30 '22 11:09

Roger Fan