我正在处理大量 csv(表格),我需要删除包含字符的单元格并保留数字单元格。
例如。
p1 p2 p3 p4 p5
dcf23e 2322 acc41 4212 cdefd
所以在这种情况下,我只想删除 dcf23e、acc41 和 cdefd。删除这些字符串后,我想将它们保留为空单元格。
我该怎么做?提前致谢。
我试过的代码是这个...,这个代码删除字符串中的字符,但问题是,如果一个字符串是 23cdgf2,它会生成一个字符串 232,这不是我想要的。删除所有字符后,当我尝试将字符串转换为 int 进行计算时,一些字符串变成了小数,因为一些字符串有 123def.24 -> 123.24
temp = ''.join([c for c in temp if c in '1234567890.']) # Strip all non-numeric characters
# Now converting strings to integers for calculations, Using function to use int() , because of the blank spaces cannot be converted to int
def mk_int(s):
s = s.strip()
return int(s) if s else 0
mk_int(temp)
print(temp)
请您参考如下方法:
为性能编译正则表达式并为正确性拆分字符串
import re
regex = re.compile(r'.*\D+.*')
def my_parse_fun(line):
return [regex.sub('', emt) for emt in line.split()]
根据AbhiP的回答,你也可以做
[val if val.isdigit() else '' for val in line.split()]
