Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
删除.CSV-Python/Pandas中一列中的空格_Python_Python 3.x_Pandas - Fatal编程技术网

删除.CSV-Python/Pandas中一列中的空格

删除.CSV-Python/Pandas中一列中的空格,python,python-3.x,pandas,Python,Python 3.x,Pandas,这就是我的“new_plates.csv”的样子- TT59 TRI,"Black,Thomas,Mr" HY63 YOJ,"Smith,Simon,Mr" YY36 DPM,"Paul & Clare,Mr & Mrs" 这是Python代码-我首先将“plates.txt”文件转换为“plates.csv”文件,然后将未使用的列过滤为“new_plates.csv”并删除旧的“plates.csv”。这很好,但我想从车牌号中删除空格,但保留在名称中。什么不起作用 导入操作系

这就是我的“new_plates.csv”的样子-

TT59 TRI,"Black,Thomas,Mr"
HY63 YOJ,"Smith,Simon,Mr"
YY36 DPM,"Paul & Clare,Mr & Mrs"
这是Python代码-我首先将“plates.txt”文件转换为“plates.csv”文件,然后将未使用的列过滤为“new_plates.csv”并删除旧的“plates.csv”。这很好,但我想从车牌号中删除空格,但保留在名称中。什么不起作用

导入操作系统
导入子流程
进口大熊猫
作为pd进口熊猫
调用(“sudo csvformat-t/home/pi/scripts/plates.txt>>/home/pi/scripts/plates.csv”,shell=True)
f=pd.read_csv(“plates.csv”)
keep_col=[11,13]
new\u f=f[keep\u col]
新建到csv(“new_plates.csv”,index=False)
new_f[1]=new_f[1].str.replace(“,”)
subprocess.call(“sudo rm/home/pi/scripts/plates.csv”,shell=True)
打印(新的)
不知道该如何正确地写这行

new\u f[1]=new\u f[1].str.replace(“,”)
我想让它看起来像这样-没有空格的车牌号

TT59TRI,"Black,Thomas,Mr"
HY63YOJ,"Smith,Simon,Mr"
YY36DPM,"Paul & Clare,Mr & Mrs"

感谢您使用
str.split().apply(“.join”)

Ex:

df=pd.read_csv("plates.csv", names=["plates", "name"])
df["plates"] = df["plates"].str.split().apply("".join)
print(df)
    plates                   name
0  TT59TRI        Black,Thomas,Mr
1  HY63YOJ         Smith,Simon,Mr
2  YY36DPM  Paul & Clare,Mr & Mrs
输出:

df=pd.read_csv("plates.csv", names=["plates", "name"])
df["plates"] = df["plates"].str.split().apply("".join)
print(df)
    plates                   name
0  TT59TRI        Black,Thomas,Mr
1  HY63YOJ         Smith,Simon,Mr
2  YY36DPM  Paul & Clare,Mr & Mrs

首先,无需将txt转换为csv,因为熊猫也可以处理txt。第二,

new_f[1] = [plate.replace(" ", "") for plate in new_f[1]]

不需要对
子流程.call()进行两次调用
pd.read\u csv()
可以在给定正确参数的情况下处理文件。文件删除可以通过以下两种方式之一完成:
os.unlink('/home/pi/scripts/plates.csv')
pathlib.Path('/home/pi/scripts/plates.csv').unlink()
df['plates']=df['plates'].str.replace(''',)
更直接,不可行,但在不需要的情况下手动迭代对于
熊猫来说确实是一种糟糕的形式。