我想通过在验证过程后保存新的CSV来删除CSV文件中的一些行。我写了下面的代码,但它导致了一个错误
with open(path_to_read_csv_file, "r") as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter=',')
for line in csv_reader:
# if validation(line[specific_column]):
try:
df = pd.DataFrame(line)
df.to_csv(path_to_save_csv_file)
except Exception as e:
print('Something Happend!')
print(e)
continue
错误:
Something Happend!
If using all scalar values, you must pass an index
我还尝试通过df = pd.DataFrame(line, index=[0])
添加一个索引值,但它只存储第一行,在开头有一个额外的空列。如何解决这个问题
另一个带有line
的版本可以工作,但我无法在每一行达到特定的键值:
inFile = open(path_to_read_csv_file, 'r')
outFile = open(path_to_save_csv_file, 'w')
for line in inFile:
try:
print('Analysing:', line)
# HERE, how can I get the specific column value? I used to use line[specific_column] in the last version
if validation(line[specific_column]):
outFile.write(line)
else:
continue
except Exception as e:
print('Something Happend!')
print(e)
continue
outFile.close()
inFile.close()
构造函数
pd.DataFrame
希望您告诉您提供的数据也必须如何索引。这被记录在案here函数
csv.DictReader
使用有关更多信息,请参阅csvdocumentation
因此,由
csv_reader
解析的每个line
都是一个字典,其中键是CSV头,值是特定行中的每一行例如,如果我的CSV是:
然后在第一次迭代中,
line
对象将是:现在,当您将其提供给
pd.DataFrame
时,需要指定数据是什么以及头/索引是什么。在这种情况下,数据是['1', '2', '3']
,头/索引是['Header1', 'Header2', 'Header3']
。这些可以分别通过调用line.values()
和line.keys()
提取这就是我所做的改变
This应该能帮助你。基本上,您不能仅从标量值创建数据帧。它们必须用例如a
list
包装起来相关问题 更多 >
编程相关推荐