代码之家  ›  专栏  ›  技术社区  ›  Davide Lorino

从列中的字符串中提取一组n个数字

  •  0
  • Davide Lorino  · 技术社区  · 6 年前

    我在熊猫数据框中有一列字符串,其中包含如下内容: "AU/4347001" 但除此之外,还有其他一些不太有组织的字符串,比如 "Who would have thought this would be so 4347009 difficult"

    因此,最终,这些数字系列在字符串中出现的位置和方式没有连贯的模式。它们可能在开头、中间或结尾,而且无法确切知道数字周围还有多少其他字符。

    理想情况下,我希望返回另一个长度相等的列,其中只包含数字。

    这有可能吗?

    非常感谢您的帮助!

    谢谢你

    4 回复  |  直到 6 年前
        1
  •  1
  •   YOLO    6 年前

    你可以做到 extract :

    df =pd.DataFrame({'text':["Who would have thought this would be so 4347009 difficult",
                              "24 is me"]})
    
    df['new_col'] = df['text'].str.extract(r'(\d+)')
    
        text                                                new_col
    0   Who would have thought this would be so 434700...   4347009
    1   24 is me                                            24
    
        2
  •  1
  •   Dani Mesejo    6 年前

    你可以使用 extract 带数字捕获组 (\d+) :

    import pandas as pd
    
    data = ["AU/4347001",
            "Who would have thought this would be so 4347009 difficult",
            "Another with a no numbers",
            "131242143"]
    
    df = pd.DataFrame(data=data, columns=['txt'])
    result = df.assign(res=df.txt.str.extract('(\d+)')).fillna('')
    print(result)
    

    产量

                                                     txt        res
    0                                         AU/4347001    4347001
    1  Who would have thought this would be so 434700...    4347009
    2                          Another with a no numbers           
    3                                          131242143  131242143
    

    注意,在上面的示例中,使用 fillna 在本例中,用空字符串填充那些没有找到数字组的列。

        3
  •  1
  •   Leo Walker    6 年前

    这是我们的测试数据框架:

    ### Create an example Pandas Dataframe
    df = pd.DataFrame(data=['something123', 'some456thing', '789somthing', 
                            'Lots of numbers 82849585 make a long sentence'], columns = ['strings'])
    
    ### Create a function for identifying, joining and then turning the string to an integer
    def get_numbers(string):
        return int(''.join([s for s in string if s.isdigit()]))
    
    ### Now lets apply the get_numbers function to the strings column
    df.loc[:,'strings_wo_numbers'] = df.loc[:,'strings']apply(get_numbers)
    

    注意:这将连接字符串中的所有数字,即“10个橄榄和5个苹果”将变为105而不是10、5。

        4
  •  0
  •   BENY    6 年前

    使用 str.finall

    df.text.str.findall('\d+').str[0]
    0    4347009
    1         24
    Name: text, dtype: object