Home > OS >  Extract consecutive uppercase words from a column of strings in Python
Extract consecutive uppercase words from a column of strings in Python

Time:05-16

I have a column of strings from which I wish to extract all consecutive uppercase words that appear in different cases. Here is an example of the type of strings I have:

data = pd.DataFrame({
    'strings': ['ubicado en QUINTA CALLE, LADO NORTE detras',
                'encuentra por AVENIDA NORTE, ARRIBA DE IGLESIA frente a',
                'direccion en CENTRO COMERCIAL, SEGUNDO NIVEL junto a']
})

The lowercase words appear frequently enough to use them as regular expressions. Here is an example of what I have done so far:

df['extraction'] = df['strings'].str.extract('(?:(?<=ubicado en )|(?<=encuentra por )|(?<=direccion en ))(.*?)(?:(?=\s*detras)|(?=\s*frente\s*a)|(?=\s*junto\s*a))')

However, I would like to find a way to only use the first lowercase words and then apply a regex that would grab all the consecutive uppercase words. Here is an example of what I am looking for

df['extraction'] = df['strings'].str.extract('(ubicado\s*en\s*<REGEX>|encuentra\s*por\s*<REGEX>|direccion\s*en\s*<REGEX>)')

This should result in the following:

data = pd.DataFrame({
    'extraction': ['QUINTA CALLE, LADO NORTE',
                'AVENIDA NORTE, ARRIBA DE IGLESIA',
                'CENTRO COMERCIAL, SEGUNDO NIVEL']
})

The strings are actually much longer and complex texts, so I cannot simply remove all lowercase letters in the column. Thanks in advance for any help you can provide!

CodePudding user response:

You can use the following:

words = '(?:ubicado|encuentra|direccion)'
regex = words '[^A-Z]*([^a-z] )'

data['extraction'] = data['strings'].str.extract(regex)

Output:

                                                   strings                         extraction
0               ubicado en QUINTA CALLE, LADO NORTE detras          QUINTA CALLE, LADO NORTE 
1  encuentra por AVENIDA NORTE, ARRIBA DE IGLESIA frente a  AVENIDA NORTE, ARRIBA DE IGLESIA 
2     direccion en CENTRO COMERCIAL, SEGUNDO NIVEL junto a   CENTRO COMERCIAL, SEGUNDO NIVEL 

Or, to avoid trailing non-letter characters:

words = '(?:ubicado|encuentra|direccion)'
regex = words '[^A-Z]*([^a-z]*[A-Z] )'

data['extraction'] = data['strings'].str.extract(regex)

Output:

                                                   strings                        extraction
0               ubicado en QUINTA CALLE, LADO NORTE detras          QUINTA CALLE, LADO NORTE
1  encuentra por AVENIDA NORTE, ARRIBA DE IGLESIA frente a  AVENIDA NORTE, ARRIBA DE IGLESIA
2     direccion en CENTRO COMERCIAL, SEGUNDO NIVEL junto a   CENTRO COMERCIAL, SEGUNDO NIVEL

CodePudding user response:

You could use a custom function to check each character for upper caps. Then use the lambda function on each cell in the DataFrame:

import pandas as pd
    
def check_upper(str):
    output = []
    for x in str:
        if x.isupper() or x==" " or x==",":
            output.append(x)
    return "".join(output).strip().strip(",")

data = pd.DataFrame({
    'strings': ['ubicado en QUINTA CALLE, LADO NORTE detras',
                'encuentra por AVENIDA NORTE, ARRIBA DE IGLESIA frente a',
                'direccion en CENTRO COMERCIAL, SEGUNDO NIVEL junto a']
})
data["strings"] = data["strings"].apply(lambda x: check_upper(x))
data

Output:

    strings
0   QUINTA CALLE, LADO NORTE
1   AVENIDA NORTE, ARRIBA DE IGLESIA
2   CENTRO COMERCIAL, SEGUNDO NIVEL
  • Related