prashantgpt91
prashantgpt91

Reputation: 1795

Edit CSV cell using pandas

How to edit CSV cell value using pandas.

I'm trying like this

obj.set_value(rowindex, 'C', val)

Where I expect the old value in row = rowindex and column = C i.e.. df[rowindex][C] should get replced by val and my original csv should get update.

I know pandas provides, inplace=True, to do that, but set_value doesn't support that. How can I do this ?

Upvotes: 1

Views: 11745

Answers (2)

DoesData
DoesData

Reputation: 7047

Changing the data frame doesn't change the csv file since they are not the same thing. You have a few options.

  1. Read the csv into a 2D list update the desired cell and the write the 2D list back to a csv file. Help

  2. Update the dataframe then use df.to_csv()

Try something like this:

df..set_value(rowindex, 'C', val)
df.to_csv(file_name, encoding='utf-8', index=False)

Upvotes: 1

michaelg
michaelg

Reputation: 954

Here is the content of the original file student.csv:

StudentID,Name,Username,Password,Moderator
0001,Foo Bar,test,abc123,N
0002,Baz Qux,bob,bcd986,Y

Load CSV

df = pd.read_csv('students.csv')

Change the cell and save back to the original file

df.set_value(0,'Name','changed')
df.to_csv('students.csv', index=False)

result

StudentID,Name,Username,Password,Moderator
1,changed,test,abc123,N
2,Baz Qux,bob,bcd986,Y

Upvotes: 3

Related Questions