0

I have a file that goes like this

AAPL, TSCO, ASDA, ....
10, 11, 12, ...
9, 10, 11, ...
...,...,...,...

Now is there a way to import a list all of these as variables of their column header. So it will beAAPL = [ 10, 9, ...,...]

I know how to print out a list of column headers using:

import pandas as pd
df = pd.read_csv('foo.csv', index_col=0)

col_headers = list(df.columns)

So now I can loop over this list, but is there a way, to automatically assign the variable name as the list header?

SamHarper
  • 105
  • 3
  • 23

2 Answers2

2

The best here is create dictonary of list and for each list select by key - here by columns name:

d = df.to_dict('list')
print (d)
{'AAPL': [10, 9], 'TSCO': [11, 10], 'ASDA': [12, 11]}

print (d['AAPL'])
[10, 9]

print (type(d['AAPL']))
<class 'list'>

What you need is possible, but not recommended:

for c in df.columns:
    globals()[c] =  df[c].tolist()

print (AAPL)
[10, 9]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • And I will be able to chage this list? i.e. size, list variables ect? As long as ts kept as a list? – SamHarper Jul 27 '19 at 16:22
  • @SamHarper - If use `d['AAPL']` is is list, use it instead `AAPL` like you mentoned in question. – jezrael Jul 27 '19 at 16:27
  • @SamHarper what do you mean by " will be able to chage this list? i.e. size, list variables ect?" – anky Jul 27 '19 at 16:46
1

Here is a solution that does not require pandas.

import csv

class MyTable:

    def __init__(self, filename):
        with open(filename, newline='') as csvfile:
            reader = csv.DictReader(csvfile)
            self.data = [row for row in reader]

    def column(self, key, cast_as = str):
        return sorted([
                cast_as(value[key]) 
                for value in self.data
            ])

# usage:
>>> dataset = MyTable("foo.csv")
>>> aapl = dataset.column('AAPL', float)
>>> print(aapl)
[10., 9.]