-1

I am currently in a class that is a beginners course for python. We have an assignment instructing us to read the contents of the data file into a floating point array data2 without using genfromtxt or any other pre-written file-reading function. Thus, you have to create a file object, use string methods to access, convert, etc. Make the first column be yyyy-mm-dd as a floating point number. I am a little bit lost as to how I would do something like this and was hoping I could get a little bit of help on methods or ways to go about this. Thank you

data2 = []
with open('sp500_1950-01-03_to_2016-10-07.csv', 'r') as myfile:
    for line in myfile:
        data = line.rsplit(',')
        data2.append(data)
print(data2)

This is what I have so far but I need every value/number to have its own index and be a float, I'm not sure how to do this.

finance.yahoo.com/quote/%5EGSPC/history?p=%5EGSPC This is the link to the data/csv file we are supposed to read. Other than that we are supposed to come up with the method ourselves.

  • Unfortunately, for us to help you, you would have to show us what you've done. I'm assuming since it's an introductory class, they would be providing you the tools to tackle this problem? – roelofs Nov 22 '17 at 02:48
  • Sorry, you'll have to write what you can, and then we can help you from there. SO is not a codewriting service. – roelofs Nov 22 '17 at 02:56

1 Answers1

0

Though question is not clear.

First question: Make the first column be yyyy-mm-dd as a floating point number, how this could be possible. say 2017.11.22, is this float you mean?

Are you looking for something like this?

   for line in open("my_file.csv"):
         line_read_as_list = line.split(',')

What's you delimiter of csv file? Concept: read as line split in list.

if your first column is in "yyyy-mm-dd" format, split line_read_as_list[0] in line_read_as_list with '-' and capture year, month and day in separate list. You should give a try yourself. There are many way to do this.

If you want to put back in the format: yyyy.mm.dd simply replace '-' by '.'. It should be string.

Pati Ram Yadav
  • 815
  • 1
  • 8
  • 22
  • A couple comments: (1) in your first list comprehension using `for i in line.split(',')`, `i` will be a string, so `isinstance(i, float)` will always be `False`; (2) you can simplify `line_read_as_list = [i for i in line.split(',')]` to `line_read_as_list = line.split(',')`, because `line.split(',')` creates a list. – Warren Weckesser Nov 22 '17 at 06:45
  • Yes, you are right! I haven't run this code. The question also doesn't have any example. I have edited. – Pati Ram Yadav Nov 23 '17 at 01:56