简体   繁体   English

熊猫从字符串中提取数字

[英]Pandas Extract Number from String

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完成,但我不确定如何。

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

要在上面的评论中回答@Steven G 的问题,这应该有效:

df.A.str.extract('(^\d*)')

您可以使用“分配”功能用您的结果替换您的列:

df = df.assign(A = lambda x: x['A'].str.extract('(\d+)'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM