Reputation: 1795
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
Reputation: 7047
Changing the data frame doesn't change the csv file since they are not the same thing. You have a few options.
Read the csv into a 2D list update the desired cell and the write the 2D list back to a csv file. Help
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
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
df = pd.read_csv('students.csv')
df.set_value(0,'Name','changed')
df.to_csv('students.csv', index=False)
StudentID,Name,Username,Password,Moderator
1,changed,test,abc123,N
2,Baz Qux,bob,bcd986,Y
Upvotes: 3