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.
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.
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.
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.
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}}
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}.
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'
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:
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}}
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