ramesh
ramesh

Reputation: 1217

Pandas: strip numbers and parenthesis from string

My pandas df:

df  = pd.DataFrame({'A':[1,2,3,4,5], 'B':['(AAAAA)2','(BCA)1','(CA)5','(DD)8','(ED)15']})
    A   B
0   1   (AAAAA)2
1   2   (BCA)1
2   3   (CA)5
3   4   (DD)8
4   5   (ED)15

I want to strip parenthsis and numbers in the column B
Expected output is:

    A   B
0   1   AAAAA
1   2   BCA
2   3   CA
3   4   DD
4   5   ED

So far I tried,

df['B'] = df['B'].str.extract('([ABCDE])')

But I only got:

    A   B
0   1   A
1   2   B
2   3   C
3   4   D
4   5   E

Upvotes: 3

Views: 6032

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210882

you can do it this way:

In [388]: df
Out[388]:
   A         B
0  1  (AAAAA)2
1  2    (BCA)1
2  3     (CA)5
3  4     (DD)8
4  5    (ED)15

In [389]: df.B = df.B.str.replace(r'[\(\)\d]+', '')

In [390]: df
Out[390]:
   A      B
0  1  AAAAA
1  2    BCA
2  3     CA
3  4     DD
4  5     ED

if you still want to use .str.extract() you can do it this way:

In [401]: df['B'].str.extract(r'.*?([A-Za-z]+).*?', expand=True)
Out[401]:
       0
0  AAAAA
1    BCA
2     CA
3     DD
4     ED

Upvotes: 6

Related Questions