【问题标题】:Python: Get numeric in a DataFrame String Object which start and end with specific wordPython:在以特定单词开头和结尾的DataFrame字符串对象中获取数字
【发布时间】:2020-12-07 10:44:36
【问题描述】:

我希望字符串数字为整数,表示出现在 totalUSD 之间的总成本。

示例数据框:

    id   name    lastname   message 
0   1   John    Doe        John have 100 USD, so he buy 5 eggs which total cost 10 USD
1   2   Mar     Aye        Mar have 10 USD, he just buy a banana from another shop for 16 USD

所以最终的结果应该是:

    id   name    lastname   message                                                             total
0   1   John    Doe        John have 100 USD, so he buy 5 eggs which total cost 10 USD         10
1   2   Mar     Aye        Mar have 10 USD, he just buy a banana from another shop for 16 USD  0

【问题讨论】:

    标签: python pandas substring nltk tokenize


    【解决方案1】:

    您可以使用正则表达式来捕获出现在“total”和“USD”之间的任何数字。

    下面的代码将捕获任何数字(如果是多个数字,则需要进行一些调整,如果应该接受浮点数,但由于类型应该是 int,所以应该不需要)并将其转换为 int 类型。

    df['total'] = df['message'].str.extract('total.*?(\d+).*?USD').fillna(0).astype(int)
    

    结果:

    id   name    lastname   message                                                             total
    0   1   John    Doe        John have 100 USD, so he buy 5 eggs which total cost 10 USD         10
    1   2   Mar     Aye        Mar have 10 USD, he just buy a banana from another shop for 16 USD  0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      • 2015-11-08
      • 2021-12-17
      • 2018-02-18
      • 2019-03-02
      • 2017-09-12
      相关资源
      最近更新 更多