Extract data from string in python

I have a .csv file with data constructed as [datetime, "(data1, data2)"] in rows and I have managed to import the data into python as time and temp, the problem I am facing is how do I seperate the temp string into two new_temp columns in float format to use for plotting later on?

My code so far is:

import csv
import matplotlib.dates as dates

def getColumn(filename, column):
    results = csv.reader(open('logfile.csv'), delimiter = ",")
    return [result[column] for result in results]
time = getColumn("logfile.csv",0)
temp = getColumn("logfile.csv",1)
new_time = dates.datestr2num(time)
new_temp = [???]

When I print temp I get ['(0.0, 0.0)', '(64.4164, 66.2503)', '(63.4768, 65.4108)', '(62.7148, 64.6278)', '(62.0408, 63.9625)', '(61.456, 63.2638)', '(61.0234, 62.837)', '(60.6823, 62.317)',...etc]

If anyone can help me then thanks in advance.

Upvotes: 0

Views: 1979

Answers (2)

CodeMonkey
CodeMonkey

Reputation: 4738

Going from the answer in Parse a tuple from a string?

from ast import literal_eval as make_tuple
temp = ['(0.0, 0.0)', '(64.4164, 66.2503)', '(63.4768, 65.4108)', '(62.7148, 64.6278)', '(62.0408, 63.9625)', '(61.456, 63.2638)', '(61.0234, 62.837)', '(60.6823, 62.317)']

tuples = [make_tuple(stringtuple) for stringtuple in temp]

and you have an array of tuples of doubles.

I undeleted the post and made it a full answer, because apparently it wasn't clear enough to reference the other post.

Upvotes: 1

Ohumeronen
Ohumeronen

Reputation: 2086

You may use this code:

import re
string = "['(0.0, 0.0)', '(64.4164, 66.2503)', '(63.4768, 65.4108)', '(62.7148, 64.6278)', '(62.0408, 63.9625)', '(61.456, 63.2638)', '(61.0234, 62.837)', '(60.6823, 62.317)']"
data = re.findall('[+-]?\d+\.\d+e?[+-]?\d*', string)
data = zip(data[0::2], data[1::2])
print [float(d[0]) for d in data]
print [float(d[1]) for d in data]

Upvotes: 1

Related Questions