Python: import csv, do math with specific cells, output new columns to new (or same) CSV -


i've been working on days-

i have csv looks like:

col || col b|| col c||

0.1 || 0.0 || 0.5 ||

0.4 || 60 || 0.6 ||

0.3 || -60 || 0.5 ||

...

0.2 || -60 || 0.4 ||

there 25 rows of numbers- vary slightly. want import csv using python, slight math (ex. finding avg between cell a1 , c1) either print new column whole new csv file or add new column beginning of current or (even duplicated) file. know the actual math part easy. it's importing, manipulation, exporting new column cannot get.

here's i've tried: 1) first tried importing csv, changing list, reading columns need exporting new csv. issue have when export csv doesn't create columns. adds things single cell (0.111, 1.002, ..).

import csv ofile=open('duplicate.csv', "w") writer=csv.writer(ofile, delimiter=',')  open('/users/mycsv.csv', 'rb') f:     mycsv = csv.reader(f)     mycsv = list(mycsv)     avg=[]     high=[]      #average number     in range(1,25):         x=float(mycsv[i][16])         avg.append(x)     #print avg     average=zip(avg)          #highest number     in range(1,25):         x=float(mycsv[i][15])         high.append(x)     #print high     highest=zip(high)         print highest  writer.writerow([average,highest])  ofile.close() 

2)then tried creating new column duplicate file , adding information column. got similar version of similar question. doesn't work- error "typeerror: can assign iterable"

import csv infilename = r'/users/mycsv.csv' outfilename = r'/users/mycsv_duplicate.csv'  open(infilename, 'rb') fp_in, open(outfilename, 'wb') fp_out:     reader = csv.reader(fp_in, delimiter=",")     writer = csv.writer(fp_out, delimiter=",")      headers = next(reader)  # read title row     headers[0:0] = ['avg']     writer.writerow(headers)      row in reader:         in range(1,25):             mycsv=list(reader)             row[0:0] = float(mycsv[i][15])         writer.writerow(row) 

i've been @ days can please help!?!?!?

i've written of in matlab need transfer on python... matlab easier figure out.

use pandas. designed for.

import pandas pd  df = pd.read_csv('test.csv', sep='\|\|', usecols=[0, 1, 2]) df['avg'] = df.loc[:, ('col a', 'col c')].mean(axis=1)  df.to_csv('test2.csv', index=false) df.to_csv('tes3.csv', index=false, columns='avg') 

Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -