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

Postby Marleb » Tue Aug 06, 2013 1:37 pm

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 line
for 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
Posts: 3
Joined: Mon Aug 05, 2013 10:08 am

Re: Calculate difference in list and write it in list

Postby stranac » Tue Aug 06, 2013 2:00 pm

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.
User avatar
Posts: 1790
Joined: Thu Feb 07, 2013 3:42 pm

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

Postby Yoriz » Tue Aug 06, 2013 5:40 pm

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

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[-2] = calculated[-2] - calculated[-1]

print calculated[:-1]

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 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.
User avatar
Posts: 1672
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

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

Postby tnknepp » Tue Aug 06, 2013 8:23 pm

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 file
data = pd.read_csv('filename.csv',etc)

# Calculate difference between subsequent lines
data = 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
User avatar
Posts: 153
Joined: Mon Mar 11, 2013 7:41 pm

Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 4 guests