简体   繁体   中英

Make new column from slice of string from one column pandas python

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM