繁体   English   中英

使用 Pandas 从文本中提取特定单词

[英]Extract specific words from text using pandas

在我的数据框中,有几个国家的名称中带有数字和/或括号。 我想从这些国家/地区名称中删除括号和数字。

例如:'Bolivia (Plurinational State of)' 应该是'Bolivia','Switzerland17' 应该是'Switzerland'。

这是我的代码,但似乎不起作用:

import numpy as np 
import pandas as pd 


def func():
    energy=pd.ExcelFile('Energy Indicators.xls').parse('Energy')
    energy=energy.iloc[16:243][['Environmental Indicators: Energy','Unnamed: 3','Unnamed: 4','Unnamed: 5']].copy()
    energy.columns=['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable']
    o="..."
    n=np.NaN
    energy = energy.replace('...', np.nan)




    energy['Energy Supply']=energy['Energy Supply']*1000000

    old=["Republic of Korea","United States of America","United Kingdom of " 
                                +"Great Britain and Northern Ireland","China, Hong "
                                +"Kong Special Administrative Region"]
    new=["South Korea","United States","United Kingdom","Hong Kong"]
    for i in range(0,4):

        energy = energy.replace(old[i], new[i])

    #I'm trying to remove it here =====> 

    p="("

    for j in range(16,243):
        if p in energy.iloc[j]['Country']:
            country=""
            for c in energy.iloc[j]['Country'] : 

                while(c!=p & !c.isnumeric()):
                    country=c+country
            energy = energy.replace(energy.iloc[j]['Country'], country)


    return energy

这是我正在处理的 .xls 文件: https : //drive.google.com/file/d/0B80lepon1RrYeDRNQVFWYVVENHM/view?usp=sharing

使用str.extract

energy['country'] = energy['country'].str.extract('(^[a-zA-Z]+)', expand=False)

df

                            country
0  Bolivia (Plurinational State of)
1                     Switzerland17

df['country'] = df['country'].str.extract('(^[a-zA-Z]+)', expand=False)
df

       country
0      Bolivia
1  Switzerland

要处理名称中带有空格的国家(非常常见),对正则表达式进行小幅改进就足够了。

df

                            country
0  Bolivia (Plurinational State of)
1                     Switzerland17
2             West Indies (foo bar)

df['country'] = df['country'].str.extract('(^[a-zA-Z\s]+)', expand=False).str.strip()
df

       country
0      Bolivia
1  Switzerland
2  West Indies

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM