Python 熊猫从字符串中提取数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37683558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas Extract Number from String
提问by Dance Party
Given the following data frame:
给定以下数据框:
import pandas as pd
import numpy as np
df = pd.DataFrame({'A':['1a',np.nan,'10a','100b','0b'],
})
df
A
0 1a
1 NaN
2 10a
3 100b
4 0b
I'd like to extract the numbers from each cell (where they exist). The desired result is:
我想从每个单元格(它们存在的地方)中提取数字。想要的结果是:
A
0 1
1 NaN
2 10
3 100
4 0
I know it can be done with str.extract
, but I'm not sure how.
我知道它可以用 来完成str.extract
,但我不确定如何。
回答by Jon Clements
Give it a regex capture group:
给它一个正则表达式捕获组:
df.A.str.extract('(\d+)')
Gives you:
给你:
0 1
1 NaN
2 10
3 100
4 0
Name: A, dtype: object
回答by Taming
To answer @Steven G 's question in the comment above, this should work:
要在上面的评论中回答@Steven G 的问题,这应该有效:
df.A.str.extract('(^\d*)')