Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 从熊猫系列(所有组)中提取所有数字字符_Regex_String_Pandas_Series - Fatal编程技术网

Regex 从熊猫系列(所有组)中提取所有数字字符

Regex 从熊猫系列(所有组)中提取所有数字字符,regex,string,pandas,series,Regex,String,Pandas,Series,我正在尝试对pandas系列使用str.extract(“(\d+”)方法来获取电话号码的数字,该电话号码看起来像:(123)456-7890 使用此方法仅返回123,但我希望输出为1234567890 一般来说,我想知道如何从字符串中获取所有数字,而不必担心组 谢谢来源DF: In [66]: x Out[66]: phone 0 (123) 456-7890 1 +321 / 555-7890 2 (111) - 666 7890 在这种情况下,使用

我正在尝试对pandas系列使用str.extract(“(\d+”)方法来获取电话号码的数字,该电话号码看起来像:(123)456-7890

使用此方法仅返回123,但我希望输出为1234567890

一般来说,我想知道如何从字符串中获取所有数字,而不必担心组

谢谢

来源DF:

In [66]: x
Out[66]:
              phone
0    (123) 456-7890
1   +321 / 555-7890
2  (111) - 666 7890
在这种情况下,使用
'\D+'
RegEx删除所有非数字要容易得多,因为它将处理任何类型的电话格式(如
+123 456789
(123)/456-789
等):

使用
Series.str.extract
您需要编写相当复杂的正则表达式来解析不同的电话格式

源DF:

In [66]: x
Out[66]:
              phone
0    (123) 456-7890
1   +321 / 555-7890
2  (111) - 666 7890
在这种情况下,使用
'\D+'
RegEx删除所有非数字要容易得多,因为它将处理任何类型的电话格式(如
+123 456789
(123)/456-789
等):

使用
Series.str.extract
您需要编写相当复杂的正则表达式来解析不同的电话格式

结果:

    no              clean
0   (123) 456-7890  1234567890
1   +321 / 555-7890 3215557890
结果:

    no              clean
0   (123) 456-7890  1234567890
1   +321 / 555-7890 3215557890

或者你也可以用熊猫替换法

df['clean'] = df['phone'].replace('\D+', '', regex = True)
或者,如果要覆盖列本身,请使用

df['clean'].replace('\D+', '', regex = True, inplace = True)

或者你也可以用熊猫替换法

df['clean'] = df['phone'].replace('\D+', '', regex = True)
或者,如果要覆盖列本身,请使用

df['clean'].replace('\D+', '', regex = True, inplace = True)

这很有效,谢谢。你能解释一下原因吗?在这种情况下,它在做什么?为什么替换比提取更好?@andrebo7,我已经扩展了我的答案-请检查这是否有效,谢谢。你能解释一下原因吗?在这种情况下,它在做什么?为什么替换比提取更好?@andrebo7,我扩展了我的答案-请检查是的,这很聪明!谢谢欣赏:)是的,这很聪明!谢谢谢谢:)是的!这就是我要找的!这就是我要找的