Reputation: 13
I have a list of dictionaries in Python with different keys (Response Key is present in all ) and I want to convert it into a Panda Dataframe such that all key-values are shown as rows with Response Key value repeating as a Column. For instance, following list
[ {'Response': 1, 'work life': 5, 'life family': 2, 'family balance': 10}, {'Response': 2, 'encouragement management': 11, 'management career': 1, 'career aspirations': 4, 'aspirations develop': 8},{'Response': 3, 'encourage people': 15, 'people managers': 9, 'managers ask': 5, 'ask employees': 9} ]
should become 3-column dataframe as
Response | Attribute | Value
1, work life, 5
1, life family, 2
1, family balance, 10
2, encouragement management, 11
2, management career, 1
2, career aspirations, 4
2, aspirations develop, 8
3, encourage people, 15
3, people managers, 9
3, managers ask, 5
3, ask employees, 9
Upvotes: 0
Views: 540
Reputation: 402844
This might be what you're looking for. Use stack
and then reset the index and column names.
df = pd.DataFrame(d).set_index('Response').stack().reset_index()
df.columns = ['Response', 'Attribute', 'Value']
df
Response Attribute Value
0 1 family balance 10.0
1 1 life family 2.0
2 1 work life 5.0
3 2 aspirations develop 8.0
4 2 career aspirations 4.0
5 2 encouragement management 11.0
6 2 management career 1.0
7 3 ask employees 9.0
8 3 encourage people 15.0
9 3 managers ask 5.0
10 3 people managers 9.0
d
is your dictionary data. Keep in mind that dictionaries are not ordered, so it is unreasonable to always expect the same order as in your question.
Upvotes: 2