1

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 ?

prashantitis
  • 1,797
  • 3
  • 23
  • 52

2 Answers2

3

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
michaelg
  • 944
  • 6
  • 12
  • exactly, though it is working for most of the rows, can you tell why it is failing for some rows. This is the stack trace `PermissionError: [Errno 13] Permission denied: 'file.csv'` – prashantitis Mar 30 '18 at 12:31
  • I cannot reproduce your error. I am using python 3.6. – michaelg Mar 30 '18 at 12:37
  • If you can show the exact code that produces your error, we may spot the problem. – michaelg Mar 30 '18 at 12:39
1

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)
DoesData
  • 6,594
  • 3
  • 39
  • 62