我为 Pandas
设置了一个函数,该函数遍历 input.csv
中的大量行并将结果输入到系列中。然后将系列写入 output.csv
。
但是,如果进程被中断(例如被意外事件中断),程序将终止,并且本应进入 csv 的所有数据都将丢失。
有没有办法将数据连续写入 csv,而不管函数是否对所有行完成?
Prefarably,每次程序启动时,都会创建一个空白的 output.csv
,在函数运行时将其附加到。
import pandas as pd
df = pd.read_csv("read.csv")
def crawl(a):
#Create x, y
return pd.Series([x, y])
df[["Column X", "Column Y"]] = df["Column A"].apply(crawl)
df.to_csv("write.csv", index=False)
最佳答案
这是一个可能的解决方案,它会在读取 block 中的 csv 时将数据附加到新文件。如果进程中断,新文件将包含中断前的所有信息。
import pandas as pd
#csv file to be read in
in_csv = '/path/to/read/file.csv'
#csv to write data to
out_csv = 'path/to/write/file.csv'
#get the number of lines of the csv file to be read
number_lines = sum(1 for row in (open(in_csv)))
#size of chunks of data to write to the csv
chunksize = 10
#start looping through data writing it to a new file for each chunk
for i in range(1,number_lines,chunksize):
df = pd.read_csv(in_csv,
header=None,
nrows = chunksize,#number of rows to read at each loop
skiprows = i)#skip rows that have been read
df.to_csv(out_csv,
index=False,
header=False,
mode='a',#append data to csv file
chunksize=chunksize)#size of data to append for each loop
关于python - Pandas:从函数连续写入 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31090127/