I have the following dataframe:
ABC ID
0 4 M01
1 3 M02
2 5 M03
When i am using df.set_index(['ID']).to_dict()
this gives me
{'ABC':{'M01':4,'M02':3,'M03':5}}
Required output is
{'M01':4,'M02':3,'M03':5}
I have the following dataframe:
ABC ID
0 4 M01
1 3 M02
2 5 M03
When i am using df.set_index(['ID']).to_dict()
this gives me
{'ABC':{'M01':4,'M02':3,'M03':5}}
Required output is
{'M01':4,'M02':3,'M03':5}
In this case, you want to turn the series defined by df['ABC']
into a dict
, not the entire DataFrame.
try: df.set_index(['ID'])['ABC'].to_dict()
, it should result in the required output.
dict
and zip
Sometimes for simple tasks like this, it's better to use straight Python and avoid the unnecessary creation of Pandas objects just to get a dictionary.
dict(zip(df['ID'], df['ABC']))
{'M01':4,'M02':3,'M03':5}