Fetch only capital words from DataFrame in Pandas

PythonServer Side ProgrammingProgramming

To fetch only capital words, we are using regex. The re module is used here and imported. Let us import all the libraries −

import re
import pandas as pd

Create a DataFrame −

data = [['computer', 'mobile phone', 'ELECTRONICS', 'electronics'],['KEYBOARD', 'charger', 'SMARTTV', 'camera']]

dataFrame = pd.DataFrame(data)

Now, extract capital words −

for i in range(dataFrame.shape[1]):
   for ele in dataFrame[i]:
      if bool(re.match(r'\w*[A-Z]\w*', str(ele))):
         print(ele)

Example

Following is the code −

import re
import pandas as pd

# create a dataframe
data = [['computer', 'mobile phone', 'ELECTRONICS', 'electronics'],['KEYBOARD', 'charger', 'SMARTTV', 'camera']]

dataFrame = pd.DataFrame(data)

# dataframe
print"Dataframe...\n",dataFrame

print"\nDisplaying only capital words...\n"

# extracting capital words
for i in range(dataFrame.shape[1]):
   for ele in dataFrame[i]:
      if bool(re.match(r'\w*[A-Z]\w*', str(ele))):
         print(ele)

Output

This will produce the following output −

Dataframe...
          0              1             2             3
0  computer   mobile phone   ELECTRONICS   electronics
1  KEYBOARD        charger       SMARTTV        camera

Displaying only capital words...

KEYBOARD
ELECTRONICS
SMARTTV
raja
Published on 20-Sep-2021 12:41:08
Advertisements