我有一张桌子(请参考图片)在这张桌子上我想删除" A"每行的字符我怎么能用Python做。
以下是使用regexe_replace
的代码但代码未优化我想要优化代码
def re(s):
return regexp_replace(s, "A", "").cast("Integer")
finalDF = finalD.select(re(col("C0")).alias("C0"),col("C1"),
re(col("C2")).alias("C2"),
re(col("C3")).alias("C3"),col("C4"),
re(col("C5")).alias("C5"),
re(col("C6")).alias("C6"),col("C7"),
re(col("C8")).alias("C8"),
re(col("C9")).alias("C9"),col("C10"),
re(col("C11")).alias("C11"),col("C12"),
re(col("C13")).alias("C13"),
re(col("C14")).alias("C14"),col("C15"),
re(col("C16")).alias("16"),col("C17"),
re(col("C18")).alias("18"),
re(col("C19")).alias("C19"),col("Label"))
finalDF.show(2)
先谢谢你。
答案 0 :(得分:2)
为何选择正则表达式?正则表达式将被杀死。
如果您提供了您提供的格式数据,请使用替换功能,如下所示:
master.csv的内容:
A11| 6|A34|A43|
A11| 6|A35|A44|
代码:
with open('master.csv','r') as fh:
for line in fh.readlines():
print "Before - ",line
line = line.replace('A','')
print "After - ", line
print "---------------------------"
输出:
C:\Users\dinesh_pundkar\Desktop>python c.py
Before - A11| 6|A34|A43|
After - 11| 6|34|43|
---------------------------
Before - A11| 6|A35|A44|
After - 11| 6|35|44|
---------------------------
代码更换' A'从一次性完成数据(不逐行)
with open("master.csv",'r') as fh:
data = fh.read()
data_after_remove = data.replace('A','')
print "Before remove ..."
print data
print "After remove ..."
print data_after_remove
<强>输出:强>
C:\Users\dinesh_pundkar\Desktop>python c.py
Before remove...
A11| 6|A34|A43|
A11| 6|A35|A44|
After remove ...
11| 6|34|43|
11| 6|35|44|
C:\Users\dinesh_pundkar\Desktop>