Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to put a dateset containes two different types of data into two different list in python using for loop only?

data for example

10/11/2015,129.177551

how do I build two lists?
Date [] and price [] should contain date and price separately

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you data is in csv, you can use pandas package:

file.csv

10/11/2015,129.177551
10/11/2015,129.177551
import pandas
df = pandas.read_csv('file.csv', header=False)
date = df.iloc[0,:].tolist()
price = df.iloc[1,:].tolist()

Though most people just leave the data in the pandas DataFrame for further processing.


If you data is in a string

data = '''10/11/2015,129.177551
10/11/2015,129.177551'''

data = [line.split(',') for line in data.split('\n')]
date, price = zip(*data)

And if you want to use for loop:

data = '''10/11/2015,129.177551
10/11/2015,129.177551'''

date = []
price = []
for line in data.split('\n'):
    d, p = line.split(',')
    date.append(d)
    price.append(p)

As you can see, method 1 (list comprehension) is much shorter.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading