I have a pandas dataframe and it looks like so:
person weight height skill
kate 160 200 100
john 170 150 70
I have set the person column as the index of my python dataframe. And then i turned it into a dictionary using the .to_dict()
method. this gives the following dictionary:
{'weight': {'kate': '160', 'john': '170'},
'height': {'kate': '200', 'john': '150'},
'skill': {'kate': '100', 'john': '70'},
I need to change the around so that the dictionary is per person, but i dont know if its possible to do in python. What i need my dictionary to look like is:
{'Kate: { weight': '160', 'height': '200', 'skill': '100'},
'John': {'weight': '170', 'height': '150', 'skill': '70'}}
Is it possible to do this?
CodePudding user response:
You can set person
as the index and use to_dict
with orient
arg set to index
.
df.set_index('person').to_dict('index')
# {'kate': {'weight': 160, 'height': 200, 'skill': 100},
# 'john': {'weight': 170, 'height': 150, 'skill': 70}}
CodePudding user response:
You can Transpose your df and use to_dict.
df.set_index('person').T.to_dict()
Output:
{'kate': {'weight': '160', 'height': '200', 'skill': '100'},
'john': {'weight': '170', 'height': '150', 'skill': '70'}}
CodePudding user response:
You can use the .to_dict() parameter orient = 'index'
to build from the indexes (if column 'pearson' is the index of your dataframe) or you can transpose the dataframe using .T and perform the .to_dict() operation
df = pd.DataFrame({'person' : ['kate', 'john'], 'weight' : [160,170], 'height' : [200,150],'skill' : [100, 70]})
df = df.set_index('person')
# Solution orient
print(df.to_dict(orient='index')
# {'kate': {'weight': 160, 'height': 200, 'skill': 100}, 'john': {'weight': 170, 'height': 150, 'skill': 70}}
# Solution transpose
print(df.T.to_dict())
# {'kate': {'weight': 160, 'height': 200, 'skill': 100}, 'john': {'weight': 170, 'height': 150, 'skill': 70}}