【问题标题】:how to replace non-numeric chars using regex如何使用正则表达式替换非数字字符
【发布时间】:2018-05-23 11:12:06
【问题描述】:

我想知道如何使用正则表达式删除任何非数字字符,同时仅以更有效的方式为系列选择非空和空格(单个值可能包含一个或多个空格)值,

df['numeric_no'] = df['id'].apply(lambda x: re.sub("[^0-9]", "", x))
df = df[(df['numeric_no'] != '') & (df['numeric_no'] != ' ')]

df 的一些示例数据

numeric_no
B-27000
44-11-E
LAND-11-4
17772A
88LL9A
321LP-3
UNIT 9 CAM -00-12
WWcard_055_34QE
EE119.45
aaa
b  b

结果会是这样的

numeric_no
27000
4411
114
17772
889
3213
90012
05534
119.45

【问题讨论】:

  • 你能添加一些数据样本吗?
  • @jezrael 示例数据已添加
  • 谢谢,所以所有行都被选中了?没有人从样本中移除?
  • @jezrael 刚刚添加了示例结果,希望清楚

标签: regex python-3.x pandas dataframe


【解决方案1】:

我相信需要str.findallboolean indexing

s = df['numeric_no'].str.findall("(\d*\.\d+|\d+)").str.join('')

s = s[s.astype(bool)]
print (s)

0     27000
1      4411
2       114
3     17772
4       889
5      3213
6     90012
7     05534
8    119.45
Name: numeric_no, dtype: object

【讨论】:

  • 我认为这是 OP 需要的,但仍需要一些澄清
【解决方案2】:

您可以匹配和捕获数字并匹配其他任何东西:

(\d+(?:\.\d+)?)|.

Live demo

然后将匹配替换为$1(对第一个捕获组的反向引用)

Python 代码:

re.sub(r"(\d+(?:\.\d+)?)|.", "$1", x) 

【讨论】:

    【解决方案3】:

    我觉得可以试试:

    df.numeric_no.str.extractall('(\d+?[\.\d+])').astype(str).sum(level=0)
    

    输出:

            0
    0    2700
    1    4411
    2      11
    3    1777
    4      88
    5      32
    6    0012
    7    0534
    8  119.45
    

    【讨论】:

    • 你的意思是\d+ 在字符类中吗?还是每一个分开? \d, +?
    猜你喜欢
    • 2011-02-03
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多