【问题标题】:Retrieving the row values in pandas检索熊猫中的行值
【发布时间】:2019-06-27 14:37:48
【问题描述】:

我有一个包含两列的数据框

countries                       data
United states of america(USA)    1
india13                          2

我想以这种格式从行中获取数据

countries                       data
United states of america        1
india                           2

简而言之,我想按括号和数字过滤索引。如果它包含其中任何一个,那么我想从行标签中删除括号和数字。我该怎么做?

【问题讨论】:

    标签: python pandas data-cleaning


    【解决方案1】:

    使用str.extract,正则表达式从字符串中提取所有字母,直到遇到括号

    df.countries = df.countries.str.extract('([A-Za-z ]+)\(?', expand = False)
    
        countries                   data
    0   Unites states of america    1
    1   india                       2
    

    【讨论】:

      【解决方案2】:

      您可以使用str.replace 来删除数字和括号以及其中的文本:

      df.loc[:,'countries'] = df.countries.str.replace(r'[0-9]|\(.*\)','', regex=True)
      
                  countries         data
      0  Unites states of america     1
      1                     india     2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-16
        • 1970-01-01
        • 1970-01-01
        • 2023-02-25
        • 2022-07-25
        • 2021-07-16
        相关资源
        最近更新 更多