从 Pandas 中的字符串中提取 int [英] Extract int from string in Pandas

查看:37
本文介绍了从 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆