我试图将整个特定列从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
但是,它一直显示"没有列从文件中解析(这意味着path_2.csv)"的错误。path_2.csv为空文件。为什么会有这样的错误呢?请帮我找出错误。
如果您的csv为空,那么显然它没有列,这就是您得到错误消息的原因。您似乎期望从dest_wb = pd.read_csv(r'path_2.csv')
生成准空的DataFrame
,但是空的df
当然也不会有第一列(dest_sheet = dest_wb.iloc[:, 0]
)。
一般来说,这里用于变量的关键字相当令人困惑。例如,当我们处理csv
读入df
时,src_wb = pd.read_csv(r"path_1.csv")
为什么是wb
?同理,dest_sheet = dest_wb.iloc[:, 0]
;如果要捕获column
,为什么要捕获sheet
?
我不确定这行应该如何执行:src_sheet = material_library_read["Desc"]
.
下面是一段通用python代码,用于打开src_csv,选择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)