Home > Back-end >  Pandas - convert first column from row to header
Pandas - convert first column from row to header

Time:06-15

I have the below dataframe coming from a long list of dictionaries (a sample looks like:

final_list = [{'name': 'total_video_followers', 'period': 'lifetime', 'values': [{'value': 10}], 'title': None, 'description': None, 'id': '5400'}, {'name': .... etc}]

the dataframe it creates when using

df_list = pd.DataFrame(final_list)
Index name period values id
0 total_video_followers lifetime [{'value': 10}] 5400
1 total_video_followers_unique lifetime [{'value': 1}] 5400

but I want to change the axis so the name column should be the headers, but also the id should be a header as well

Index total_video_followers total_video_followers_unique id period
0 [{'value': 10}] [{'value': 1}] 5400 lifetime

I tried pivot and transpose but it didn't work:

pivoted = df_list.pivot(columns='name').reset_index()

transpose = df_list.T

when I try the last line, transpose, the headers are 0, 1, 2....

CodePudding user response:

Conseder pivoting your dataframe

df.pivot(['id', 'period'], 'name', 'values').reset_index()
 
name    id    period total_video_followers total_video_followers_unique
0     5400  lifetime       [{'value': 10}]               [{'value': 1}]
  • Related