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

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

How can i make 10 to 2010?
Your answer solved my question. upvoted it and will accept as soon as I am allowed
@ShailajaGuptaKapoor - all datetimes are >2000 ? Then use df['year']= 2000 + df.index.str[3:5].astype(int)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.