Read a single column of a CSV and store in an array

csv, pandas, python

Solution

One option is just to read in the entire csv, then select a column:

data = pd.read_csv("data.csv")

data['title']  # as a Series
data['title'].values  # as a numpy array

As @dawg suggests, you can use the usecols argument, if you also use the squeeze argument to avoid some hackery flattening the values array...

In [11]: titles = pd.read_csv("data.csv", sep=',', usecols=['title'], squeeze=True)

In [12]: titles  # Series
Out[12]: 
0    abc
1    cde
Name: title, dtype: object

In [13]: titles.values  # numpy array
Out[13]: array(['abc', 'cde'], dtype=object)

Problem

What is the best way to read from a csv, but only one specific column, like `title`? ``` ID | date| title | ------------------- 1| 2013| abc | 2| 2012| cde | ``` The column should then be stored in an array like this: ``` data = ["abc", "cde"] ``` This is what I have so far, with pandas: ``` data = pd.read_csv("data.csv", index_col=2) ``` I've looked into this thread. I still get an `IndexError: list index out of range`. EDIT: It's not a table, it's comma seperated like this: ``` ID,date,title 1,2013,abc 2,2012,cde ```

Original source

Related problems