从Pandas中的字符串中提取int [英] Extract int from string in Pandas
本文介绍了从Pandas中的字符串中提取int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个数据框df
作为
Lets say I have a dataframe df
as
A B
1 V2
3 W42
1 S03
2 T02
3 U71
我想有一个新列(可以在列df
的末尾或用它替换列B
,因为这没关系),该列只能从列B
中提取int.那就是我希望列C
看起来像
I want to have a new column (either at it the end of df
or replace column B
with it, as it doesn't matter) that only extracts the int from the column B
. That is I want column C
to look like
C
2
42
3
2
71
因此,如果数字前面有0,例如03,那么我想返回3而不是03
So if there is a 0 in front of the number, such as for 03, then I want to return 3 not 03
我该怎么做?
推荐答案
您可以转换为字符串并使用正则表达式提取整数.
You can convert to string and extract the integer using regular expressions.
df['B'].str.extract('(\d+)').astype(int)
这篇关于从Pandas中的字符串中提取int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文