python - 将一列拆分为具有不同数据类型的两列
问题描述
我试图分隔此列中的最后一位数字以便放入另一列,因为最后一位数字对应于产品的体积。目前该列如下所示:
Producto
0 SIR EDWARD'S BLENDED 70
1 SIR EDWARD'S BLENDED 70
2 SIR EDWARD'S BLENDED 70
3 DILLON BLANCO 100
4 SAINT JAMES BLANC 55º 100
Name: Producto, dtype: object
我希望它看起来像这样:
Producto | CL
0 SIR EDWARD'S BLENDED | 70
1 SIR EDWARD'S BLENDED | 70
2 SIR EDWARD'S BLENDED | 70
3 DILLON BLANCO | 100
4 SAINT JAMES BLANC 55º | 100
Name: Producto, dtype: object
解决方案
您可以使用.str.rsplit()
,如下所示:
df[['Producto', 'CL']] = df['Producto'].str.rsplit(' ', n=1, expand=True)
如果要将列转换CL
为整数,可以进一步使用:
df['CL'] = df['CL'].astype(int)
结果:
print(df)
Producto CL
0 SIR EDWARD'S BLENDED 70
1 SIR EDWARD'S BLENDED 70
2 SIR EDWARD'S BLENDED 70
3 DILLON BLANCO 100
4 SAINT JAMES BLANC 55º 100
推荐阅读
- logging - JMeter 忽略 FATAL/OFF 日志级别
- swift - 如何在 UINavigationBar 中水平居中 UIBarButtonItems
- wordpress - 如何禁用 elementor(插件)的 Slick JS 库?
- cakephp - Cakephp 3.0 批量插入
- javascript - 如何解决:系统找不到指定的文件 - JS相关的.reduce()
- reactjs - 在 react-admin 的 SelectInput 中使用来自 graphql 自省的 enumValues
- kvm - 可以虚拟机的CPU频率
- hyperledger-fabric - 如何通过给定键获取日期范围内的历史记录
- mysql - 在 MYSQL 中使用触发器以更好地扩展的最佳替代方法是什么?
- php - Yii2:如何获取其属性在数组中的记录?