首页 > 解决方案 > 将一列拆分为具有不同数据类型的两列

问题描述

我试图分隔此列中的最后一位数字以便放入另一列,因为最后一位数字对应于产品的体积。目前该列如下所示:

             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

标签: pythonpython-3.xpandasdataframe

解决方案


您可以使用.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

推荐阅读