簡體   English   中英

Python Pandas:如何從數據框列中拆分括號上的列?

[英]Python Pandas: How to split a column on parenthesis from a column of dataframe?

我有一個熊貓數據框:

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

我試圖將列產品分成兩列,如

       Product      Room  Price
 0   Berlin Stret    E10   12
 1   Paris Ave       C12   34
 2   5th Ave         D30   56

我試着用

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

你可以使用正則表達式extract

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

輸出(小寫產品新欄目):

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

或者使用正則表達式'|' 拆分:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM