首页 > 解决方案 > 从一列pandas python中的字符串切片创建新列

问题描述

我在链接 [Text] 上阅读了答案(Pandas 从另一列的字符串切片创建新列),但它并没有解决我的问题。

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

等等

现在我想要列月和年,它将从 SKU 列中获取值并返回 Jan 月和 10 年(2010 年)。

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

我得到 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')

请帮忙

标签: pythonpandas

解决方案


我认为第一列是索引,所以使用.index,也可以将切片year更改为,可以省略:4:53:500: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

推荐阅读