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

时间:2017-10-22 01:12:25

标签: python pandas dataframe

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

例如: '玻利维亚(多民族国)'应该是'玻利维亚', '瑞士17'应该是'瑞士'。

这是我的代码,但似乎无效:

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

1 个答案:

答案 0 :(得分:1)

使用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
相关问题