## Do calculations on file rows and make results into a list

This is the place for queries that don't fit in any of the other categories.

### Do calculations on file rows and make results into a list

I want to calculate row2-row1, row3-row2 and so on and put the value into a new list. Anybody an idea?

Code: Select all
`import csv   data = open("example.csv", "rb")lines = []for line in data.xreadlines():   print linefor i in range (len(data) - 1):   fk = data[i+1] - data[i]   print fk`
Last edited by Yoriz on Tue Aug 06, 2013 5:33 pm, edited 2 times in total.
Reason: Added code tags, changed title
Marleb

Posts: 3
Joined: Mon Aug 05, 2013 10:08 am

### Re: Calculate difference in list and write it in list

stranac wrote:Read this before posting again.
It explains how to post properly.

Read that topic and edit your post or you won't get help. Ever.
Also, this doesn't belong in tutorials, moving to general coding help.
Friendship is magic!

R.I.P. Tracy M. You will be missed.

stranac

Posts: 1790
Joined: Thu Feb 07, 2013 3:42 pm

### Re: Do calculations on file rows and make results into a lis

It depends on how your example.csv is laid out but if it just pure numbers in each row like this
Code: Select all
`1005030.5155.2`

You could use something like this
Code: Select all
`with open('example.csv') as row:    calculated = [float(next(row).strip())]    for item in row:        calculated.append(float(item.strip()))        calculated[-2] = calculated[-2] - calculated[-1]print calculated[:-1]`

Output
Code: Select all
`[50.0, 19.5, 15.5, 9.8]`

If your file is not like that you will have to adjust it and error check for non numeric characters ect.
Due to the reasons discussed here we will be moving to python-forum.io/ on October 1 2016
This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.

Yoriz

Posts: 1672
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

### Re: Do calculations on file rows and make results into a lis

Reading line by line if a great way to go. However, if you can read in the whole file you can make use of other tools.

Code: Select all
`import pandas as pd# Load filedata = pd.read_csv('filename.csv',etc)# Calculate difference between subsequent linesdata = data.diff()`

Of course, there is more than can be done (and likely more that needs to be done to catch the details of your file), but that depends on your application.
Python: 2.7 via Anaconda
Numpy: 1.7
Pandas: 0.11
OS: Windows 7
IDE: Spyder/IPython

tnknepp

Posts: 153
Joined: Mon Mar 11, 2013 7:41 pm