Skip to content
Advertisement

How to insert data into a specific cell in csv with python?

I am trying to insert data into a specific cell in csv. My code is as follows.

The existing file.

enter image description here

Output

The data in cell A1(“Custmor”) is replaced with new data(“Name”).

enter image description here

My code is as follows.

import pandas as pd

#The existing CSV file
file_source = r"C:UsersuserDesktopCustomer.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)

And it doesn’t work. Please help me finding the bug.

Advertisement

Answer

Customer is column header, you need do

df = df.rename(columns={'Customer': 'Name'})
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement