0

Heres what my data looks like: enter image description here

What I'm trying to accomplish is add columns 3 and 4 together and create a new column right next to column 4 in the csv file before the column with the "right, left" options

For example the values in the new column would be:

7
7
7
7
7

Here is my code for doing this which is not working:


def computed_column(csvfile):
    with open(csvfile,newline='') as f:
        with open('combined_csv.csv','w',newline='') as f2:
            writer = csv.writer(f2)
            rows = csv.reader(f)
            for row in rows:
                y=[]
                y.append(int(row[2]) + int(row[3]))
                writer.writerow(row+y)

The Don
  • 43
  • 11
  • 1
    Please [create a reproducible copy of the DataFrame with `df.head(20).to_clipboard(sep=',')`](https://stackoverflow.com/questions/52413246/how-to-provide-a-copy-of-your-dataframe-with-to-clipboard), [edit] the question, and paste the clipboard into a code block. – Trenton McKinney Jul 16 '20 at 22:52
  • 1
    Add code, errors, and data as text, not screenshots because [Stack Overflow Discourages Screenshots](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors). It is likely the question will be down-voted and closed. You are discouraging assistance because no one wants to retype your data or code, and screenshots are often illegible. [edit] the question and add text. – Trenton McKinney Jul 16 '20 at 22:52
  • csv file is a text file; you can add lines (rows) to an existing file. To add columns you need to write a whole new file. That means load the file into Python object (dataframe), make changes there, and then write the new file. – hpaulj Jul 16 '20 at 23:15
  • Please provide a sample file/data to give you working code and avoid posting images of data. Thank you. – Ehsan Jul 16 '20 at 23:49

1 Answers1

1

Ideally you want this (without data, it is hard to show you results):

import pandas as pd

df = pd.read_csv(csvfile)
new_col = (df[[2]]+df[[3]]).tolist()
df.insert(loc=4, column='sum', value=new_col)
df.to_csv('combined_csv.csv')
Ehsan
  • 12,072
  • 2
  • 20
  • 33