0

I read the answer at the link [Text] (Pandas make new column from string slice of another column), but it does not solve my problem.

df

  SKU        Noodles    FaceCream  BodyWash   Powder      Soap 
 Jan10_Sales    122        100        50        200         300
 Feb10_Sales    100        50         80        90          250
 Mar10_sales    40         30         100       10          11

and so on

Now I want column month and year which will take value from SKU Column and return Jan for month and 10 for year (2010).

 df['month']=df['SKU'].str[0:3]
 df['year']=df['SKU'].str[4:5]

I get KeyError: 'SKU'

Doing other things to understand why the error, I perform the following:

 [IN]df.index.name
 [OUT]None

  [IN]df.columns
  [OUT]Index(['Noodles','FaceCream','BodyWash','Powder','Soap'], dtype='object', name='SKU')

Please help

noob
  • 3,601
  • 6
  • 27
  • 73

1 Answers1

1

I think first column is index, so use .index, also for year change 4:5 slicing to 3:5, 0 is possible omit in 0:3:

df['month']=df.index.str[:3]
df['year']=df.index.str[3:5]
print (df)
             Noodles  FaceCream  BodyWash  Powder  Soap month year
SKU                                                               
Jan10_Sales      122        100        50     200   300   Jan   10
Feb10_Sales      100         50        80      90   250   Feb   10
Mar10_sales       40         30       100      10    11   Mar   10
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252