0

I have a df as shown below

product     bought_date      number_of_sales 
A           2016             15
A           2017             10
A           2018             15
B           2016             20
B           2017             30
B           2018             20
C           2016             20
C           2017             30
C           2018             20

From the above I would like to add one column called cost_per_unit as shown below.

cost of product A is 100, B is 500 and C is 200

d1 = {'A':100, 'B':500, 'C':'200'}

Expected Output:

product     bought_date      number_of_sales   cost_per_unit
A           2016             15                100
A           2017             10                100
A           2018             15                100
B           2016             20                500
B           2017             30                500
B           2018             20                500
C           2016             20                200
C           2017             30                200
C           2018             20                200
Danish
  • 2,719
  • 17
  • 32

2 Answers2

1

No need for any lambda function. Run just:

df['cost_per_unit'] = df['product'].map(d1)

Additional remark: product is a name of a Pandas function. You should avoid column names "covering" existing functions or attributes. It is a good habit, that they should differ, at least in char case.

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
0

You can try this:

df['cost_per_unit'] = df.apply(lambda x: d1[x['product']], axis=1)
print(df)

  product  bought_date  number_of_sales cost_per_unit
0       A         2016               15           100
1       A         2017               10           100
2       A         2018               15           100
3       B         2016               20           500
4       B         2017               30           500
5       B         2018               20           500
6       C         2016               20           200
7       C         2017               30           200
8       C         2018               20           200
NYC Coder
  • 7,424
  • 2
  • 11
  • 24