【问题标题】:How to extract specific content in a pandas dataframe with a regex?如何使用正则表达式提取熊猫数据框中的特定内容?
【发布时间】:2016-07-01 22:26:01
【问题描述】:

考虑以下 pandas 数据框:

In [114]:

df['movie_title'].head()

​
Out[114]:

0     Toy Story (1995)
1     GoldenEye (1995)
2    Four Rooms (1995)
3    Get Shorty (1995)
4       Copycat (1995)
...
Name: movie_title, dtype: object

更新: 我想用正则表达式提取电影的标题。因此,让我们使用以下正则表达式:\b([^\d\W]+)\b。所以我尝试了以下方法:

df_3['movie_title'] = df_3['movie_title'].str.extract('\b([^\d\W]+)\b')
df_3['movie_title']

但是,我得到以下信息:

0       NaN
1       NaN
2       NaN
3       NaN
4       NaN
5       NaN
6       NaN
7       NaN
8       NaN

知道如何从 pandas 数据框中的文本中提取特定特征吗?更具体地说,如何在全新的数据框中仅提取电影的标题?例如,期望的输出应该是:

Out[114]:

0     Toy Story
1     GoldenEye
2    Four Rooms
3    Get Shorty
4       Copycat
...
Name: movie_title, dtype: object

【问题讨论】:

    标签: python regex string python-2.7 pandas


    【解决方案1】:

    我想提取符号“@”之后和符号“.”之前的文本。 (句号)我试过这个,它或多或少地工作,因为我有符号“@”但我不想要这个符号,无论如何:

    df['col'].astype(str).str.extract('(@.+.+)
    

    【讨论】:

      【解决方案2】:

      使用正则表达式查找括号之间存储的年份。 我们指定了括号,这样我们就不会与有多年历史的电影发生冲突 他们的头衔

      movies_df['year'] = movies_df.title.str.extract('(\(\d\d\d\d\))',expand=False)
      

      去掉括号:

      movies_df['year'] = movies_df.year.str.extract('(\d\d\d\d)',expand=False)
      

      从“标题”列中删除年份:

      movies_df['title'] = movies_df.title.str.replace('(\(\d\d\d\d\))', '')
      

      应用 strip 函数去除可能出现的任何结尾空白字符:

      movies_df['title'] = movies_df['title'].apply(lambda x: x.strip())
      

      【讨论】:

        【解决方案3】:

        您应该使用() 分配文本组,如下所示以捕获其中的特定部分。

        new_df['just_movie_titles'] = df['movie_title'].str.extract('(.+?) \(')
        new_df['just_movie_titles']
        

        pandas.core.strings.StringMethods.extract

        StringMethods.extract(pat, flags=0, **kwargs)

        使用传递的正则表达式在每个字符串中查找组

        【讨论】:

          【解决方案4】:

          您可以尝试str.extractstrip,但最好使用str.split,因为电影名称也可以是数字。下一个解决方案是 replace 括号内容由 regexstrip 前导和尾随空格:

          #convert column to string
          df['movie_title'] = df['movie_title'].astype(str)
          
          #but it remove numbers in names of movies too
          df['titles'] = df['movie_title'].str.extract('([a-zA-Z ]+)', expand=False).str.strip()
          df['titles1'] = df['movie_title'].str.split('(', 1).str[0].str.strip()
          df['titles2'] = df['movie_title'].str.replace(r'\([^)]*\)', '').str.strip()
          print df
                    movie_title      titles      titles1      titles2
          0  Toy Story 2 (1995)   Toy Story  Toy Story 2  Toy Story 2
          1    GoldenEye (1995)   GoldenEye    GoldenEye    GoldenEye
          2   Four Rooms (1995)  Four Rooms   Four Rooms   Four Rooms
          3   Get Shorty (1995)  Get Shorty   Get Shorty   Get Shorty
          4      Copycat (1995)     Copycat      Copycat      Copycat
          

          【讨论】:

          • 我知道了:TypeError: extract() got an unexpected keyword argument 'expand'
          • 您是否将pandas 更新到版本0.18.0?检查它print pd.show_versions()
          • 我更新并得到了这个:AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas。现在我有:byteorder: little LC_ALL: None LANG: None pandas: 0.18.0 nose: 1.3.7 pip: 8.1.0
          • 感谢您的帮助...只是另一个问题,为什么在使用astype(str) 时出现以下异常:UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128)。注意文件的编码是encoding='iso-8859-1,我已经准备好在pandas数据框中设置它,但是,我得到了之前的异常......我应该如何处理这个编码问题?
          • 是:df = pd.read_csv('ml-100k/u.item', \ sep = '|',names = ['movie_id','movie_title','release_date', \ 'video_release_date', 'IMDb-URL','unknown','Action','Adventure',\ 'Animation', 'Childrens','Comedy','Crime','Documentary'\ ,'Drama','Fantasy','Film-Noir','Horror','Musical','Mystery',\ 'Romance','Sci-Fi','Thriller', 'War' ,'Western'],encoding='iso-8859-1')
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-10-23
          • 2018-11-24
          • 2023-02-04
          • 2021-03-13
          • 1970-01-01
          • 2017-03-29
          • 2022-01-20
          相关资源
          最近更新 更多