从python中的列中删除数字
我想删除Python数据帧中某个列的条目中的所有数字。不幸的是,像从python中的列中删除数字,python,string,pandas,Python,String,Pandas,我想删除Python数据帧中某个列的条目中的所有数字。不幸的是,像.join()和.find()这样的命令是不可移植的(当我定义一个函数来迭代条目时,它会给我一个消息,浮动变量没有.find和.join属性)。熊猫有没有什么命令来处理这个问题 def remove(data): for i in data if not i.isdigit(): data='' data=data.join(i) return data myfile['col
.join()
和.find()
这样的命令是不可移植的(当我定义一个函数来迭代条目时,它会给我一个消息,浮动变量没有.find
和.join
属性)。熊猫有没有什么命令来处理这个问题
def remove(data):
for i in data if not i.isdigit():
data=''
data=data.join(i)
return data
myfile['column_name']=myfile['column_name'].apply(remove())
没有数据样本无法确定,但您的代码暗示
data
包含字符串,因为您在元素上调用isdigit
假设上述情况,有很多方法可以实现您的愿望。其中之一是条件列表理解:
import pandas as pd
s = pd.DataFrame({'x':['p','2','3','d','f','0']})
out = [ x if x.isdigit() else '' for x in s['x'] ]
# Output: ['', '2', '3', '', '', '0']
您可以删除以下所有数字:
import pandas as pd
df = pd.DataFrame ( {'x' : ['1','2','C','4']})
df[ df["x"].str.isdigit() ] = "NaN"
或者使用
pd.to_numeric
witherrors='concurve'
将列强制转换为数值并消除非数值:
使用@Raidex安装程序:
s = pd.DataFrame({'x':['p','2','3','d','f','0']})
pd.to_numeric(s['x'], errors='coerce')
输出:
0 NaN
1 2.0
2 3.0
3 NaN
4 NaN
5 0.0
Name: x, dtype: float64
0 p
1 NaN
2 NaN
3 d
4 f
5 NaN
Name: x, dtype: object
0 NaN
1 2
2 3
3 NaN
4 NaN
5 0
Name: x, dtype: object
编辑以处理任一情况
s['x'].where(~s['x'].str.isdigit())
输出:
0 NaN
1 2.0
2 3.0
3 NaN
4 NaN
5 0.0
Name: x, dtype: float64
0 p
1 NaN
2 NaN
3 d
4 f
5 NaN
Name: x, dtype: object
0 NaN
1 2
2 3
3 NaN
4 NaN
5 0
Name: x, dtype: object
或
输出:
0 NaN
1 2.0
2 3.0
3 NaN
4 NaN
5 0.0
Name: x, dtype: float64
0 p
1 NaN
2 NaN
3 d
4 f
5 NaN
Name: x, dtype: object
0 NaN
1 2
2 3
3 NaN
4 NaN
5 0
Name: x, dtype: object
提供一个前后数据帧示例会很有帮助,这样我们就可以准确地确定您的意思和需要。我应该解释得更好,我想做的是将tin1t9in之类的条目转换为tintin,这意味着删除列中条目的数字字符。但这并不是删除数字?@ChristianSloper Nope,你看到了输出结果。那么你没有回答这个问题吗?@ChristianSloper,好的。如果你这样说。我会按他的要求让行动组扩大范围。谢谢你的意见。他说。。如何删除数字,并演示如何删除非数字?我看不出你是怎么回答这个问题的,但我肯定。