我有一个名为 new.csv 的 csv 文件,我正在尝试删除名为 code 的特定列中的所有前导 0。
id,name,code <br>
0,kevin,010 <br>
1,john,011 <br>
2,casey,020 <br>
3,micheal,030
这只是 csv 文件的一个示例,只不过有近 1000 行。我只想从代码列中删除前导 0。
我正在尝试找到一个可以编辑整个列以供将来引用的解决方案。例如,假设我想从列中删除一个前导字符“k”。
我在网上看到了一些例子,但没有用。
这就是下面的内容
import pandas as pd
import sys
with open('new.csv') as infile:
title = next(infile)
infile.seek(0)
table = pd.read_csv(infile)
table.rename(columns={'Unnamed: 2':''}, inplace=True)
table['code'] = table['code'].str.replace("0", "")
sys.stdout.write(title)
table.to_csv(sys.stdout, ',', index=False)
最佳答案
您可以使用正则表达式re.sub
轻松替换前导零。使用这个正则表达式,
0+([1-9][0-9]*)
并替换为 \1
基本上是 group1 内容
<强> Demo
尝试这些 Python 代码,
import re
s = '''id,name,code <br>
0,kevin,010 <br>
1,john,011 <br>
2,casey,020 <br>
3,micheal,030'''
print(re.sub(r'0+([1-9][0-9]*)', r'\1', s))
打印不带前导零的数字,
id,name,code <br>
0,kevin,10 <br>
1,john,11 <br>
2,casey,20 <br>
3,micheal,30
编辑:
您可以创建这种函数,它将文件名作为参数并生成一个名为 inputfilename.out
import re
from shutil import move
from os import remove
def remove_leading_chars(inputfile):
with open(inputfile, 'r', encoding="utf-8") as infile, open(inputfile+'.out', 'w', encoding="utf-8") as outfile:
for s in infile.readlines():
s = re.sub(r',m+', r',', s)
outfile.write(s)
remove_leading_chars('data.txt')
remove('data.txt')
move('data.txt.out', 'data.txt')
print('writing done')
输入文件data.txt
的内容
id,name,code <br>
0,mmmkevin,010 <br>
1,mmmjohn,011 <br>
2,mmmcasey,020 <br>
3,mmmicheal,030
覆盖的data.txt
文件的内容
id,name,code <br>
0,kevin,010 <br>
1,john,011 <br>
2,casey,020 <br>
3,icheal,030
关于python - 删除特定 csv 文件中的前导 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55855012/