繁体   English   中英

从一列pandas python中的字符串切片创建新列

[英]Make new column from slice of string from one column pandas python

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

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 和年份(2010)的 10。

 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')

请帮忙

我认为第一列是索引,所以使用.index ,同样对于year更改4:5切片到3:50可以在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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