如何将列从一个文件复制到另一个空文件?

How to copy a column from a file to another empty file?

我正在尝试将整个特定列从 csv 文件复制到空 csv 文件。我的代码如下

import pandas as pd
#path_1.csv is the original csv file having the contents I want to copy
src_wb = pd.read_csv(r"path_1.csv")
#path_2.csv is an empty csv file
dest_wb = pd.read_csv(r'path_2.csv')

#Getting the column named "Desc" from the original file
src_sheet = material_library_read["Desc"]
#Getting the first column in the empty file
dest_sheet = dest_wb.iloc[:, 0]

#Inserting the column named "Desc" in path_1.csv into the first column in path_2.csv
dest_wb.insert(0, src_sheet)

#Saving path_2.csv after the copy complete.
dest_sheet.save

但是,它一直显示“No columns to parse from file (which means path_2.csv)”的错误。 path_2.csv 是一个空文件。为什么会出现这样的错误?请帮我找出错误。

如果您的 csv 是空的,那么显然它没有列,这就是您收到错误消息的原因。您似乎期望从 dest_wb = pd.read_csv(r'path_2.csv') 生成 quasi-empty DataFrame,但是空的 df 当然也不会有第一列(dest_sheet = dest_wb.iloc[:, 0]) .

总的来说,变量的关键字在这里比较混乱。例如。 src_wb = pd.read_csv(r"path_1.csv"),为什么 wb,当我们处理一个 csv 读入一个 df?同样,dest_sheet = dest_wb.iloc[:, 0];为什么 sheet 如果你想捕获一个 column?

我不确定这行应该如何执行:src_sheet = material_library_read["Desc"]

这是一些通用的 python 代码,用于打开 src_csv、select 1 列并将其保存到另一个 csv:

import pandas as pd

file_source = "source.csv"
file_dest = "dest.csv"

df = pd.read_csv(file_source)

#'column1' being the name of your column 
series_col = df.loc[:,'test1'] 

# series to csv as column (without index) and saves csv
series_col.to_csv(file_dest, index=False)