[英]Splitting a column into two columns with different data types
我試圖將這一列中的最后一位數字分開,以便放入另一列,因為最后一位數字對應於產品的體積。 目前該列如下所示:
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
使用 regexp 和str.extact
來提取信息。
dfn = df['Producto'].str.extract(r'(.*)\s+(\d+)$')
dfn.columns = ['Producto', 'CL']
dfn['CL'] = dfn['CL'].astype(int)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.