我正在嘗試將整個特定列從 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 是一個空檔案。為什么會出現這樣的錯誤?請幫助我找到錯誤。
uj5u.com熱心網友回復:
如果您的 csv 為空,則顯然它沒有列,這就是您收到錯誤訊息的原因。DataFrame您似乎期望從 生成準空dest_wb = pd.read_csv(r'path_2.csv'),但空df當然也不會有第一列(dest_sheet = dest_wb.iloc[:, 0])。
一般來說,用于變數的關鍵詞在這里相當混亂。例如src_wb = pd.read_csv(r"path_1.csv"),為什么wb,當我們處理對 a 的csv讀入時df?同樣,dest_sheet = dest_wb.iloc[:, 0]; 為什么sheet要捕獲一個column?
我不確定這條線應該如何執行: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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/483590.html
