2

I have been trying to extract the uppercase substring from pandas dataframe but to avail. How to extract only uppercase sub string in pandas?

Here is my MWE:

MWE

import numpy as np
import pandas as pd


df = pd.DataFrame({'col': ['cat', 'cat.COUNT(example)','cat.N_MOST_COMMON(example.ord)[2]']})
df['feat'] = df['col'].str.extract(r"[^A-Z]*([A-Z]*)[^A-Z]*")


print(df)

"""
                                 col feat
0                                cat  NaN
1                 cat.COUNT(example)    T
2  cat.N_MOST_COMMON(example.ord)[2]    N
""";

Expected output

                                 col feat
0                                cat  
1                 cat.COUNT(example)    COUNT
2  cat.N_MOST_COMMON(example.ord)[2]    N_MOST_COMMON
cs95
  • 330,695
  • 80
  • 606
  • 657
BhishanPoudel
  • 1
  • 15
  • 87
  • 137

3 Answers3

3

How about:

 df['feat'] = df.col.str.extract('([A-Z_]+)').fillna('')

Output:

                                 col           feat
0                                cat               
1                 cat.COUNT(example)          COUNT
2  cat.N_MOST_COMMON(example.ord)[2]  N_MOST_COMMON
Quang Hoang
  • 131,600
  • 10
  • 43
  • 63
  • I appreciate the extract method. Actually I had wanted to extract `agg` and `feat` from the string. Intead of updating this question I am going to ask new question as a follow up. – BhishanPoudel Oct 20 '20 at 20:04
  • I have more complicated question for using extract here: https://stackoverflow.com/questions/64452644/how-to-extract-the-uppercase-as-well-as-some-substring-from-pandas-dataframe-usi – BhishanPoudel Oct 20 '20 at 20:13
2

If you say you have only one upper-case word in each cell, you may also use replace

df['feat'] = df['col'].str.replace(r"[^A-Z_]", '')

Out[681]:
                                 col           feat
0                                cat
1                 cat.COUNT(example)          COUNT
2  cat.N_MOST_COMMON(example.ord)[2]  N_MOST_COMMON
Andy L.
  • 24,086
  • 3
  • 14
  • 26
1

You can use re.sub() with pattern [^A-Z|_]:

import re
df = pd.DataFrame({'col': ['cat', 'cat.COUNT(example)','cat.N_MOST_COMMON(example.ord)[2]']})
df['feat'] = df['col'].apply(lambda x: re.sub('[^A-Z|_]', '', x))
df
Out[1]: 
                                 col           feat
0                                cat               
1                 cat.COUNT(example)          COUNT
2  cat.N_MOST_COMMON(example.ord)[2]  N_MOST_COMMON
David Erickson
  • 15,734
  • 2
  • 16
  • 32