簡體   English   中英

如何僅提取括號之間的字符串組件?

[英]How to extract only the string component between parenthesis?

我正在尋找一種從數據列中刪除特定元素的有效方法。

我有這樣的數據:

year
1 (1991)
10 (1991-2001)
8 (1991-1998)
2 (2000-2002)

我想成為這樣:

year
1991
1991 - 2001
1991 - 1998
2000 - 2002

我想刪除括號前后的括號和元素。

使用正則表達式:

df = pd.DataFrame({'year': ['1 (1991)', '10 (1991-2001)', '8 (1991-1998)', '2 (2000-2002)']})

           year
       1 (1991)
 10 (1991-2001)
  8 (1991-1998)
  2 (2000-2002)

df['year'] = df['year'].str.extract(r'\((.*)\)')

      year
      1991
 1991-2001
 1991-1998
 2000-2002

您可以使用以下代碼

df['year'] = df['year'].str.split('(').str[1].str.strip(')')

output

    year
0   1991
1   1991-2001
2   1991-1998
3   2000-2002

怎么樣:

df['year'] = df['year'].str[1:-1]

如果您的數據並不總是以'()'開頭/結尾,則更安全:

# str.strip accepts regex
df['year'] = df['year'].str.strip('(|)')

Output:

1          1991
10    1991-2001
8     1991-1998
2     2000-2002
Name: year, dtype: object
lines = [
  "year",
  "1 (1991)",
  "10 (1991-2001)",
  "8 (1991-1998)",
  "2 (2000-2002)"
]
formatted_lines = []
for line in lines:
  updated_line = line.split('(') # Splits it into two lines: ["1 ", "1991)"]
  updated_line = updated_line.replace(')') # remove extra parenthesis
  formatted_lines.append(updated_line)

暫無
暫無

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

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