-2

I have following data from df

   proid  sku  qty 
0  p009  SKPK  0.0  
1  p009  SKKP  2.0  
2  p008  SKPK  0.0  
3  p008  SKC1  4.0  
4  p008  SKKP  0.0  

To qty column i want to add value to 'qty' based on value in 'sku'. the value are present as follows

starterkit = {"SKKP":4,'SKP1':3,'SKP1':3,'SKPK':1,'SKC1':1 }

want to do something like

if df.sku == 'SKKP' df.qty += starterkit['SKKP']

Resulting data frame should be

   proid  sku  qty 
0  p009  SKPK  1.0  
1  p009  SKKP  6.0  
2  p008  SKPK  1.0  
3  p008  SKC1  5.0  
4  p008  SKKP  4.0 
ila
  • 920
  • 12
  • 35

2 Answers2

1

Use map:

starterkit = {"SKKP":4,'SKP1':3,'SKP1':3,'SKPK':1,'SKC1':1 }
df.qty += df.sku.map(starterkit)
print (df)
  proid   sku  qty
0  p009  SKPK  1.0
1  p009  SKKP  6.0
2  p008  SKPK  1.0
3  p008  SKC1  5.0
4  p008  SKKP  4.0
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

You can use pd.Series.map:

df['qty'] += df['sku'].map(starterkit)

This is an example of a vectorised calculation. A principle benefit of using pandas is the ability to perform such calculations without resorting to Python-level loops.

jpp
  • 159,742
  • 34
  • 281
  • 339