为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

SMILET 2021-10-19 09:33:53
我在 Pandas 数据框中有一列字符串,其中包含以下内容:"AU/4347001"但此外还有其他组织较少的字符串,例如"Who would have thought this would be so 4347009 difficult"因此,最终,对于这些数字系列将出现在字符串中的位置和方式,没有一致的模式。它们可能在开头、中间或结尾,并且无法确切知道数字周围有多少其他字符。理想情况下,我想返回另一列仅包含数字的等长列。这可能吗?任何帮助是极大的赞赏!
查看完整描述

3 回答

?
慕雪6442864

TA贡献1812条经验 获得超5个赞

你可以这样做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    


查看完整回答
反对 回复 2021-10-19
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

您可以将提取与数字的捕获组一起使用(\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来填充那些没有找到数字组的列,在这种情况下,用空字符串填充。


查看完整回答
反对 回复 2021-10-19
?
湖上湖

TA贡献2003条经验 获得超2个赞

这是我们的测试 DataFrame:


### 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。


查看完整回答
反对 回复 2021-10-19
  • 3 回答
  • 0 关注
  • 170 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号