【问题标题】:Extract integral parts from strings in dataframe columns of lists从列表的数据框列中的字符串中提取整数部分
【发布时间】:2018-02-19 07:31:16
【问题描述】:

如果我有一列数据如:

           value
1    [a_1, a_342, a_452]   
2    [a_5, a_99]   
3    [a_482, a_342, a_452, a_888] 

我需要将该列修剪为:

           value
1    [1, 342, 452]   
2    [5, 99]   
3    [482, 342, 452, 888]

基本上,我想删除a_ 并使列的每个条目成为整数列表

我尝试使用基于 pandas python 包replacemap 函数,但这些都不起作用。

对于列中的单个条目,例如:

    value
1    a_1 
2    a_5  
3    a_99

我可以使用df['value'] = df['value'].str[2:].astype(int) 之类的东西,但是,这不适用于上面的字符串列表。

如果你能给我任何建议,我真的很感激。提前谢谢你。

【问题讨论】:

    标签: python string list pandas dataframe


    【解决方案1】:

    选项 1

    为了让生活更轻松,只需转换为str,使用str.replace,然后在结果上应用ast.literal_eval

    import ast
    
    df['value'] = df['value'].astype(str).str.replace('a_', '')\
               .apply(lambda x: [int(y) for y in ast.literal_eval(x)])
    df 
    
                      value
    1         [1, 342, 452]
    2               [5, 99]
    3  [482, 342, 452, 888]
    

    选项 2

    使用df.extractall

    df['value'] = df['value'].astype(str).str.extractall('(\d+)').unstack()\
                                  .apply(lambda x: list(x.dropna().astype(int)), 1)
    df 
    
                      value
    1         [1, 342, 452]
    2               [5, 99]
    3  [482, 342, 452, 888]
    

    df['value'].tolist()
    [[1, 342, 452], [5, 99], [482, 342, 452, 888]]
    

    【讨论】:

      【解决方案2】:

      用途:

      #get list of strings
      df['value'] = df['value'].astype(str).str.findall('\d+')
      #convert them to ints
      df['value'] = [[int(i) for i in x] for x in df['value']]
      #alternative
      #df['value'] = [list(map(int, x)) for x in df['value']]
      print (df)
                        value
      1         [1, 342, 452]
      2               [5, 99]
      3  [482, 342, 452, 888]
      

      使用列表推导的解决方案:

      import re
      
      df['value'] = [[int(re.findall('\d+', i)[0]) for i in x] for x in df['value']]
      print (df)
                        value
      1         [1, 342, 452]
      2               [5, 99]
      3  [482, 342, 452, 888]
      

      替代方案:

      df['value'] = [[int(re.search('\d+', i).group()) for i in x] for x in df['value']]
      

      以及replace 在正则表达式中sub 的解决方案:

      df['value'] = [[int(re.sub('[_a]', '', i)) for i in x] for x in df['value']]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-11
        • 2019-06-02
        • 2010-12-26
        • 1970-01-01
        • 2022-10-07
        • 1970-01-01
        • 2021-01-31
        • 2021-08-21
        相关资源
        最近更新 更多