如何仅提取括号之间的字符串成分?

问题描述 投票:0回答:4

我正在寻找一种从数据列中删除特定元素的有效方法。

我有这样的数据:

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

而且我想成为这样:

year
1991
1991 - 2001
1991 - 1998
2000 - 2002

我想删除括号之前和之后的括号和元素。

python regex pandas etl data-cleaning
4个回答
2
投票

带有正则表达式:

()

1
投票

您可以使用下面的代码

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(')')

0
投票

怎么样:

    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('(|)')

-2
投票
1          1991
10    1991-2001
8     1991-1998
2     2000-2002
Name: year, dtype: object
© www.soinside.com 2019 - 2024. All rights reserved.