Reputation: 140
I'm trying to reshape a dataframe. Making my column to a row, but the first column controls the rows length.
i tried pandas pivot_table to reshape the column. Example: Would like it to look.
ID Apex max min angle
1 A1 30.1 -16.9 NA
2 A1 89 NA NA
3 B1 100 26.3 68.9
ID Parameter Simulated
1 Apex A1
1 max 30.1
1 min -16.9
2 Apex A1
2 max 89
3 Apex B1
3 max 100
3 min 26.3
3 angle 68.9
df1 = pd.DataFrame({'ID': [1, 1, 1, 2, 2, 3, 3, 3, 3],
'Parameter': ['Apex', 'max', 'min', 'Apex ', 'max',
'Apex', 'max', 'min', 'angle'],
'Simulated': ['A1', 30.1, -16.9, 'A1', 89,
'B1', 100, 26.3, 68.9],
},
index=[0, 1, 2, 3, 4, 5, 6, 7, 8])
pd.pivot_table(df1, index = 'ID', columns ='Parameter', values = 'Simulated')
I'm getting this Error - DataError: No numeric types to aggregate
Thank you for what ever help you can give me.
Upvotes: 2
Views: 57
Reputation: 153500
Try:
df1.pivot(index='ID', columns='Parameter', values='Simulated')
Output:
Parameter Apex angle max min
ID
1 A1 NaN 30.1 -16.9
2 A1 NaN 89 NaN
3 B1 68.9 100 26.3
pivot_table
assumes your are going to aggregate values, by default it will use 'mean', since you have strings, in your data to pivot it is causing the error.
Multiple entries:
df1.groupby(['ID','Parameter']).first()['Simulated'].unstack().reset_index()
Upvotes: 2
Reputation: 48752
In [43]: df1.set_index(['ID', 'Parameter']).unstack()
Out[43]:
Simulated
Parameter Apex Apex angle max min
ID
1 A1 NaN NaN 30.1 -16.9
2 NaN A1 NaN 89 NaN
3 B1 NaN 68.9 100 26.3
Upvotes: 1