Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading data from a csv file and display in list of tuples

Does anyone have an idea on how to write a function loading_values(csvfilename) that takes a string corresponding to the name of the data file and returns a list of tuples containing the subset name (as a string) and a list of floating point data values. the result should be something like this when the function is called

>>> stat = loading_values(`statistics.csv`)
>>> stat
     [('Pressure', [31.52, 20.3, ..., 27.90, 59.58]),
      ('Temp', [97.81, 57.99, ..., 57.80, 64.64]),
      ('Range', [79.10, 42.83, ..., 68.84, 26.88])]

for now my code returns separate tuples for each subheading not joined by (,)

f=open('statistics.csv', 'r')
for c in f:
    numbers = c.split(',')
    numbers = (numbers[0], (numbers[1::]))

[('Pressure', [31.52, 20.3, ..., 27.90, 59.58])
 ('Temp', [97.81, 57.99, ..., 57.80, 64.64])
 ('Range', [79.10, 42.83, ..., 68.84, 26.88])]
like image 614
katto ch Avatar asked Sep 28 '22 00:09

katto ch


1 Answers

Try:

def loading_values(csvfile):
    f=open(csvfile, 'r')
    results = []
    for line in f:
        numbers = list(map(lambda x: x.strip(), line.split(',')))
        results.append((numbers[0], numbers[1:]))

    return results

print loading_values(`statistics.csv`)

or you may use csv module:

import csv
with open('statistics.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    results = map( lambda x: (x[0],x[1:]), reader)
like image 102
Assem Avatar answered Oct 03 '22 06:10

Assem