python - 从一列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')
请帮忙
解决方案
我认为第一列是索引,所以使用.index
,也可以将切片year
更改为,可以省略:4:5
3:5
0
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
推荐阅读
- react-native - 不变违规:TurboModuleRegistry.getEnforcing(...): 'DevSettings' 找不到
- wpf - SyncFusion SfRichTextBoxAdv 打字时出现奇怪的悬念
- javascript - 来自 Fauna DB 的反向数据
- php - $this->request->getData() 升级到 CakePHP 4.0 后为空
- javascript - 如何使用 nuxtjs 在 vue 模板上添加标题和脚本
- php - 我的 whereJsonContains 不起作用(Laravel 5.8)
- node.js - 整理中的强度参数在 Mongoose 中不起作用
- android - 如何使用 LiveData 在 ListItemView 中显示名称而不是 id?
- flutter - 我应该从小部件访问状态还是将其传递给 Flutter 中的状态对象?
- ios - 我的 playerCard 的初始化不起作用