我正在尝试将txt转换为csv,并将该csv读取为dataframe。但是在写入csv并删除所有空列时,还有一个额外的空列仍然保留。我不知道如何在将其写入csv文件时将其删除。
“ Face.txt”包含用','分隔的值。我已使用dropna删除了空值,如下面的代码所示
import csv
with open('Face.txt', 'r') as in_file:
stripped = (line.strip() for line in in_file)
lines = (line.split(",") for line in stripped if line)
with open('Face.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('ImageName', 'Valence','property1','property2','property3','property4','property5','property6','property7','property8','property9','property10','property11','property12','property13','property14','property15','property16','property17','property18','property19','property20','property21','property22'))
writer.writerows(lines)
这将导致Face.csv中出现其他空列。因此:-
from pandas.io.parsers import read_csv
data = read_csv('Face.csv')
filtered_data = data.dropna(axis='columns', how='all')
filtered_data.to_csv('Face2.csv')
即使尝试了上面的代码,仍然有1列为空。
我期望的是:-
ImageName |价| property1 ......
Name1.mat |负数| 0.02212 ......
我所看到的:-
................... |图片名称|价| property1 ......
Name1.mat | ................... |负| 0.02212 ......
Face.csv
ImageName |价| property1 | property2 | property3 | property4 ......
Name1.mat | ........ |负数| ......... | 0.02212 | ..........