Emotional Damage
Emotional Damage

Reputation: 148

Append a column to an existing csv file in python

This question has been asked before but those solutions didn't work for me. I have a csv file, example.csv, with data in the following format:

grid,u,lambda
0.0,0.0,-93000
0.01,-0.01,-93000
0.02,0.05,-93000

Now I have a function f.fraction('function') which returns me [1.00000000e+00 1.00000000e+00 1.00000000e+00]. I want to append this to the same file, example.csv. the final result:

grid,u,lambda,new_function
0.0,0.0,-93000,1.00000000e+00
0.01,-0.01,-93000,1.00000000e+00
0.02,0.05,-93000,1.00000000e+00

How can I do this?

Upvotes: 0

Views: 1164

Answers (1)

Diego Ramirez Vasquez
Diego Ramirez Vasquez

Reputation: 146

you can read the file first using pandas, append the new column and then save it.

import pandas as pd
df = pd.read_csv('example.csv')
df['new_function'] = f.fraction('function')
df.to_csv('example.csv')

Upvotes: 1

Related Questions