add a new categorical column to an existing table python

Solutions on MaxInterview for add a new categorical column to an existing table python by the best coders in the world

showing results for - "add a new categorical column to an existing table python"
Valentina
27 Jan 2019
1d = df.groupby('Item_Identifier')['Sales'].mean().to_dict()
2print (d)
3{'Beef': 3030.0, 'Milk': 1233.3333333333333, 'Tea': 150.0}
4
5print (df['Item_Identifier'].map(d))
60    1233.333333
71    1233.333333
82    1233.333333
93    3030.000000
104    3030.000000
115     150.000000
126     150.000000
137     150.000000
14Name: Item_Identifier, dtype: float64
15
16bins = [df['Sales'].min(),500, 1500, df['Sales].max()]
17labels=['low','medium','high']
18df['Price Category'] = pd.cut(df['Item_Identifier'].map(d), bins=bins, labels=labels)
19print (df)
20  Item_Identifier  Sales Price Category
210            Milk    500         medium
221            Milk   1200         medium
232            Milk   2000         medium
243            Beef     60           high
254            Beef   6000           high
265             Tea    150            low
276             Tea    100            low
287             Tea    200            low
29