【问题标题】:Python replace non digit character in a dataframe [duplicate]Python替换数据框中的非数字字符[重复]
【发布时间】:2019-01-02 03:53:45
【问题描述】:

我有以下数据框列

>>> df2['Age]

1    25
2    35
3    48 y
4    34 yea
5    29
...

我只想保留数字并像那样替换 df2['Age] 中的值

1    25
2    35
3    48
4    34
5    29
...

我的代码不起作用:

df2.Age.replace('^.*','^[0-9]*[0-9]',regex=True,inplace=True)

这是结果

 1    ^[0-9]*[0-9]
 2    ^[0-9]*[0-9]
 3    ^[0-9]*[0-9]
 4    ^[0-9]*[0-9]
 5    ^[0-9]*[0-9]
 ...

提前感谢您的帮助

【问题讨论】:

    标签: python regex python-3.x dataframe


    【解决方案1】:

    使用str.extract

    例如:

    import pandas as pd
    
    df = pd.DataFrame({"Age": ['25', '35', '48 y', '34 yea', '29']})
    df["Age"] = df["Age"].str.extract(r"(\d+)", expand=False)
    print(df)
    

    输出:

      Age
    0  25
    1  35
    2  48
    3  34
    4  29
    

    【讨论】:

      【解决方案2】:

      使用\D+ 将非数字替换为空字符串:

      df2.Age.replace('\D+','',regex=True,inplace=True)
      print (df2)
        Age
      1  25
      2  35
      3  48
      4  34
      5  29
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-02
        • 1970-01-01
        • 2021-02-21
        • 2019-02-19
        • 2013-06-11
        • 1970-01-01
        • 2017-11-12
        相关资源
        最近更新 更多