从Pandas中的字符串中提取int

2024-10-04 07:26:17 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个数据帧dfas

A B
1 V2
3 W42
1 S03
2 T02
3 U71

我希望有一个新列(在df的末尾,或者用它替换B列,因为这无关紧要),它只从B列中提取int。这就是我希望列C看起来像

C
2
42
3
2
71

因此,如果数字前面有一个0,比如03,那么我想返回3而不是03

我该怎么做


Tags: 数据df数字v2int末尾dfass03
3条回答

可以使用正则表达式将其转换为字符串并提取整数

df['B'].str.extract('(\d+)').astype(int)

假设始终只有一个引导字母

df['B'] = df['B'].str[1:].astype(int)

首先设置数据

df = pd.DataFrame({'A': [1, 3, 1, 2, 3], 'B' : ['V2', 'W42', 'S03', 'T02', 'U71']})

df.head()

然后执行提取并将其转换回ints

df['C'] = df['B'].str.extract('(\d+)').astype(int)

df.head()

相关问题 更多 >