从 Pandas 中的数据帧中仅获取大写单词


要仅获取大写单词,我们使用正则表达式。这里是 re 模块的使用,并进行导入。让我们导入所有库 −

import re
import pandas as pd

创建一个数据帧 −

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

dataFrame = pd.DataFrame(data)

现在,提取大写单词 −

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)

示例

代码如下 −

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)

输出

这将产生以下输出 −

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

Displaying only capital words...

KEYBOARD
ELECTRONICS
SMARTTV

更新于:2021-09-20

135 次观看

开启 职业生涯

完成课程即可获得认证

开始
广告