【问题标题】:python pandas extracting numbers within text to a new columnpython pandas将文本中的数字提取到新列
【发布时间】:2018-06-13 06:04:55
【问题描述】:

我在 A中有以下文字:

A   
hellothere_3.43  
hellothere_3.9

我只想提取数字到另一个新列 B(A 旁边),例如:

B                      
3.43   
3.9

我使用:str.extract('(\d.\d\d)', expand=True),但这复制只有 3.43(即确切的位数)。有没有办法让它更通用?

非常感谢!

【问题讨论】:

    标签: python pandas extract


    【解决方案1】:

    使用正则表达式。

    例如:

    import pandas as pd
    
    df = pd.DataFrame({"A": ["hellothere_3.43", "hellothere_3.9"]})
    df["B"] = df["A"].str.extract("(\d*\.?\d+)", expand=True)
    print(df)
    

    输出:

                     A     B
    0  hellothere_3.43  3.43
    1   hellothere_3.9   3.9
    

    【讨论】:

      【解决方案2】:

      我认为字符串拆分和应用 lambda 非常干净。

      import pandas as pd
      
      df = pd.DataFrame({"A": ["hellothere_3.43", "hellothere_3.9"]})
      df["B"] = df['A'].str.split('_').apply(lambda x: float(x[1]))
      

      我没有进行任何适当的比较,但它似乎比小型测试的正则表达式解决方案更快。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-07-07
        • 2019-12-01
        • 1970-01-01
        • 2018-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多