I have the following data frame and want to create a pivot table out of it.
Data Frame
ID value
A 0.093392
A 0.130599
A 0.257946
A 0.274428
B 0.38097
B 0.321893
A 0.279304
D 0.305667
C 0.563479
F 0.216861
A 0.252754
A 0.259845
A 0.370912
E 0.190137
E 0.180974
E 0.178766
E 0.194251
G 0.208918
C 0.495991
D 0.449585
D 0.286733
D 0.425436
D 0.411018
B 0.374447
D 0.214219
A 0.357509
E 0.257467
E 0.058252
E 0.088913
D 0.17993
What I do is the following:
df.index = df['ID']
df_pvt = df.pivot_table(values='value',index='ID', columns=['value'], aggfunc='mean')
But I get
KeyError: 'value'
As far I understand, when I place columns
as value
and values
as something else, it works, but I still do not get the desired data frame, as then instead of having one values
column I get as many column as I have values.
Below is what the desired output should look like:
ID Value
A 0.252965444
B 0.359103333
C 0.324656429
D 0.529735
E 0.216861
F 0.164108571
G 0.208918
It seems you don't need pivot_table here. You can use groupby to achieve desired result
df.groupby('ID')['Value'].mean()
Without groupby
df.set_index('ID').value.mean(level=0)
Out[26]:
ID
A 0.252965
B 0.359103
D 0.324655
C 0.529735
F 0.216861
E 0.164109
G 0.208918
Name: value, dtype: float64
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.