1

I want to store a csv file in an array in python removing the first column. In order to store it I just write these 2 lines of code

from numpy import genfromtxt
def csvToArray():
    data = genfromtxt('SP500Index.csv', delimiter=',')
    return array

and it worked. From this point how can I get rid of the first column?

2
  • 1
    If you happen to know the number of columns you're working with (num_cols), then you can directly get the columns you want through the genfromtext method: data = genfromtxt('SP500Index.csv', delimiter=',', usecols = range(1,num_cols)). Commented Dec 15, 2016 at 12:42
  • Thank you! I did not know about the usecols parameter. Commented Dec 15, 2016 at 13:04

1 Answer 1

1

Just use the numpy.delete function. Add it to the code as follows:

import numpy as np

def csvToArray():
    data = np.genfromtxt('SP500Index.csv', delimiter=',')
    data = np.delete(data, 0, 1) # the first input is the array, second is
                          #   which row/column to delete, third
                          #   determines if it is row (0) or column (1)
    return data #not sure why it had array before

Numpy's delete documentation is here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.