如何从pandas数据框中特定列的所有值中删除所有非数字字符?

编程入门 行业动态 更新时间:2024-10-22 19:32:28
本文介绍了如何从pandas数据框中特定列的所有值中删除所有非数字字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个看起来像这样的数据框:

I have a dataframe which looks like this:

A B C 1 red78 square big235 2 green circle small123 3 blue45 triangle big657

我需要能够从C列的所有行中删除非数字字符,以便数据框看起来像这样:

I need to be able to remove the non-numeric characters from all the rows in column C so that my dataframe looks like:

A B C 1 red78 square 235 2 green circle 123 3 blue45 triangle 657

我尝试使用以下命令,但得到了错误的预期字符串或缓冲区:

I tried using the following but get the error expected string or buffer:

import re dfOutput.imgID = dfOutput.imgID.apply(re.sub('[^0-9]','', dfOutput.imgID), axis = 0)

我该怎么办?

创建数据框的代码:

dfObject = pd.DataFrame() dfObject.set_value(1, 'A', 'red78') dfObject.set_value(1, 'B', 'square') dfObject.set_value(1, 'C', 'big235') dfObject.set_value(2, 'A', 'green') dfObject.set_value(2, 'B', 'circle') dfObject.set_value(2, 'C', 'small123') dfObject.set_value(3, 'A', 'blue45') dfObject.set_value(3, 'B', 'triangle') dfObject.set_value(3, 'C', 'big657')

推荐答案

使用str.extract并传递正则表达式模式以仅提取数字部分:

Use str.extract and pass a regex pattern to extract just the numeric parts:

In[40]: dfObject['C'] = dfObject['C'].str.extract('(\d+)', expand=False) dfObject Out[40]: A B C 1 red78 square 235 2 green circle 123 3 blue45 triangle 657

如果需要,可以强制转换为int:

If needed you can cast to int:

dfObject['C'] = dfObject['C'].astype(int)

更多推荐

如何从pandas数据框中特定列的所有值中删除所有非数字字符?

本文发布于:2023-06-13 17:42:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/686701.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:框中   字符   数字   数据   pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!