I have a DataFrame with four columns. I want to convert this DataFrame to a python dictionary. I want the elements of first column be keys
and the elements of o
Suppose your dataframe is as follows:
>>> df
A B C ID
0 1 3 2 p
1 4 3 2 q
2 4 0 9 r
set_index
to set ID
columns as the dataframe index. df.set_index("ID", drop=True, inplace=True)
orient=index
parameter to have the index as dictionary keys. dictionary = df.to_dict(orient="index")
The results will be as follows:
>>> dictionary
{'q': {'A': 4, 'B': 3, 'D': 2}, 'p': {'A': 1, 'B': 3, 'D': 2}, 'r': {'A': 4, 'B': 0, 'D': 9}}
column_order= ["A", "B", "C"] # Determine your preferred order of columns
d = {} # Initialize the new dictionary as an empty dictionary
for k in dictionary:
d[k] = [dictionary[k][column_name] for column_name in column_order]