Reputation: 37
I am trying to create a column, in my dataframe, which will calculate values on behalf of certain categories in another column.
Lets say, I have a column X, which has materials of different types, and there is a price of each of the types. Now, I want to append a column, based on each group along with Materials column, stating the Median of that particular type of materials.
Columns would be like Materials|Prices| Median_Prices
Help me in generating Column Median Prices.
Material,Prices,Median _Prices
a,12,12.5
a,13,12.5
b,34,34
b,565,34
b,8,34
c,87,66
c,66,66
c,7,66
Upvotes: 2
Views: 200
Reputation: 153460
No need for loops to do this. Let use groupby
and transform
:
df['Median_Prices_Calc'] = df.groupby('Material')['Prices'].transform('median')
Output:
Material Prices Median_Prices Median_Prices_Calc
0 a 12 12.5 12.5
1 a 13 12.5 12.5
2 b 34 34.0 34.0
3 b 565 34.0 34.0
4 b 8 34.0 34.0
5 c 87 66.0 66.0
6 c 66 66.0 66.0
7 c 7 66.0 66.0
Upvotes: 2