【问题标题】:Extract the first number from a string number range从字符串数字范围中提取第一个数字
【发布时间】:2022-11-02 14:50:59
【问题描述】:

我有一个数据集,其中价格列作为字符串类型,一些值采用范围(15000-20000)的形式。 我想提取第一个数字并将整列转换为整数。

我试过这个:

df['ptice'].apply(lambda x:x.split('-')[0])

代码只返回原始列。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    尝试以下选项之一:

    数据

    import pandas as pd
    
    data = {'price': ['0','100-200','200-300']}
    df = pd.DataFrame(data)
    
    print(df)
    
         price
    0        0 # adding a str without `-`, to show that this one will be included too
    1  100-200
    2  200-300
    

    选项1

    • 使用Series.str.splitexpand=True 并从结果中选择第一列。
    • 接下来,链接Series.astype,并将结果分配给df['price'] 以覆盖原始值。
    df['price'] = df.price.str.split('-', expand=True)[0].astype(int)
    
    print(df)
    
       price
    0      0
    1    100
    2    200
    

    选项 2

    • Series.str.extract 与正则表达式模式一起使用r'(d+)-?'
    • d 匹配一个数字。
    • + 匹配数字 1 次或多次。
    • 当我们点击- 时匹配停止(? 指定“如果存在”)。
    data = {'price': ['0','100-200','200-300']}
    df = pd.DataFrame(data)
    df['price'] = df.price.str.extract(r'(d+)-?').astype(int)
    
    # same result
    

    【讨论】:

      【解决方案2】:

      这是执行此操作的一种方法:

      df['price'] = df['price'].str.split('-', expand=True)[0].astype('int')
      

      这将只存储范围中的第一个数字。示例:从 15000 到 20000,只有 15000 将存储在 price 列中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-12
        • 1970-01-01
        • 1970-01-01
        • 2015-02-08
        • 2020-02-12
        相关资源
        最近更新 更多