0

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:\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)

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

2 Answers 2

2

Customer is column header, you need do

df = df.rename(columns={'Customer': 'Name'})
Sign up to request clarification or add additional context in comments.

Comments

-1

I am assuming you are going to want to work with header less csv so if that's the case, your code is already correct, just need to add header=None while reading from 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

1 Comment

The cell the OP tries to modify is a header. Trying to consider headers as part of the data is a very bad choice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.