I am trying to copy a whole specifit column from a csv file to an empty csv file. My code is as follows.
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
However, it keeps showing the error of "No columns to parse from file (which means path_2.csv)". The path_2.csv is an empty file. Why does it have such an error? Please help me finding the bug.
CodePudding user response:
If your csv is empty, then evidently it has no columns, which is why you get the error message. You seem to expect a quasi-empty DataFrame
to be generated from dest_wb = pd.read_csv(r'path_2.csv')
, but an empty df
of course wouldn't have a first column either (dest_sheet = dest_wb.iloc[:, 0]
).
In general, the key words used for the variables are rather confusing here. E.g. src_wb = pd.read_csv(r"path_1.csv")
, why wb
, when we're dealing with a csv
read into a df
? Similarly, dest_sheet = dest_wb.iloc[:, 0]
; why sheet
if you want to capture a column
?
I'm not sure how this line is supposed to execute: src_sheet = material_library_read["Desc"]
.
Here's a bit of generic python code to open a src_csv, select 1 column and save it to another 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)