我正在嘗試將資料插入到 csv 中的特定單元格中。我的代碼如下。
現有檔案。

輸出
單元格 A1("Custmor") 中的資料被替換為新資料("Name")。

我的代碼如下。
import pandas as pd
#The existing CSV file
file_source = r"C:\Users\user\Desktop\Customer.csv"
#Read the existing CSV file
df = pd.read_csv(file_source)
#Insert"Name"into cell A1 to replace "Customer"
df[1][0]="Name"
#Save the file
df.to_csv(file_source, index=False)
它不起作用。請幫助我找到錯誤。
uj5u.com熱心網友回復:
Customer是列標題,你需要做
df = df.rename(columns={'Customer': 'Name'})
uj5u.com熱心網友回復:
我假設您將要使用 header less csv 所以如果是這種情況,您的代碼已經正確,只需要header=None在從 csv 讀取時添加
import pandas as pd
#The existing CSV file
file_source = r"C:\Users\user\Desktop\Customer.csv"
#Read the existing CSV file
df = pd.read_csv(file_source,header=None) #notice this line is now different
#Insert"Name"into cell A1 to replace "Customer"
df[1][0]="Name"
#Save the file
df.to_csv(file_source, index=False,header=None) #made this header less too
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/483586.html
