如何从 Pandas 数据框中特定列中的所有值中删除所有非数字字符? [英] How can I remove all non-numeric characters from all the values in a particular column in pandas dataframe?
本文介绍了如何从 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 数据框中特定列中的所有值中删除所有非数字字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文