将新列添加到现有的.CSV/Parquet文件中,而不首先加载整个文件并重新保存?



我知道在Pandas中,您可以使用"append"模式向文件添加新行,但我想知道,是否有一种方法可以向现有文件添加新列,而不必首先加载文件,如:

df = pd.read_csv/excel/parquet("the_file.csv")

我问这个问题的原因是,有时我正在处理巨大的数据集,当我想做的只是在文件中添加1列时,将它们加载到内存中是非常昂贵的。

作为一个例子,我已经存储了一个巨大的数据集,我从该数据集加载一列来执行计算,这给了我另一列的数据。现在我想添加新列,相同长度的行和所有东西,到文件中,而不是先导入它。可能吗?

如果需要,这里是一个可复制的代码。我在更大的数据集上使用这个,但前提是完全相同的:

from sklearn.datasets import make_classification
from pandas import DataFrame, read_csv
# Make a fake binary classification dataset
X, y = make_classification(n_samples=100, n_features=10, n_informative=5, n_classes=2)
# Turn it into a dataframe
df = DataFrame(X, columns=['col1','col2','col3','col4','col5','col6','col7','col8','col9','col10'])
df['label'] = y
# Save the file
df.to_csv("./the_file.csv", index=False)
# Now, load one column from that file
main_col = read_csv("./the_file.csv", usecols=["col1"])
# Perform some random calculation to get a new column
main_col['new_col'] = main_col / 2

现在,如何将main_col['new_col']添加到./the_file.csv,而不首先导入整个文件,添加列,然后重新保存?

在处理我在评论中收到的一些反馈时,这里是我对这个问题的hack解决方案。效率不高,甚至不能正常工作,但可以让它工作。使用它作为我想要完成的伪代码表示。我也会研究一下@RakeshKumar的大块大小:

# Idea 1
# Start a new file. The columns are known, so this is fine, tho not very efficient
import csv
columns = ['col1','col2','col3','col4','col5','col6','col7','col8','col9','col10','label','added_col']
with open('new_file.csv','a') as f:
writer = csv.writer(f)
writer.writerow(columns)
# Used in a while loop
keepGoing = True
# A skip rows counter
skipRows = 0
# As long as we don't run into import issues....
while keepGoing:
try:
# Read in one line from the file
df = read_csv("./the_file.csv", nrows=1, skiprows=skipRows, header=0)
# Perform your calculation
df['added_col'] = df['col10'] / 2
# Write the new row to the new file
writer.writerow(df.iloc[0,:])
# Do the next line
skipRows+=1

# Once we've run out of rows in first file, stop the loop
except:
break

实际上,我们每次只从第一个文件中读取一行,附加到新文件中,然后当我们完成后,我们可以删除第一个文件。效率不高,但在使用大型数据集时可以降低内存负载!

最新更新