Python Pandas:如何从dataframe的列中拆分圆括号中的列?

2024-09-28 13:23:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据框:

In [8]: test
 Out[8]: 
           Product           Price
0      Berlin Stret (E10)     12
1      Paris Ave (C12)        34
2      5th Ave (D30)          56

我试图将列产品分成两列,例如

^{pr2}$

我试着用

df['Product'], df['Room'] = df['Product'].str.split('()', 1).str

Tags: 数据intestdfproductoutpriceparis
1条回答
网友
1楼 · 发布于 2024-09-28 13:23:45

可以将regex与extract一起使用:

df[['product','room']]= df.Product.str.extract('(.)\s\((.\d+)', expand=True)

输出(小写产品新列):

^{pr2}$

或使用带拆分的正则表达式“|”:

df[['product','room']] = df.Product.str.split('\(|\)', expand=True).iloc[:,[0,1]]

输出:

   Product  Price product room
0  A (E10)     12      A   E10
1  B (C12)     34      B   C12
2  C (D30)     56      C   D30

相关问题 更多 >

    热门问题