Zanam
Zanam

Reputation: 4807

Python: creating variable name from header row in csv read

I have looked for the answered questions but my case is different.

I am reading a large csv file with a header row and has 50 names in the header corresponding to 50 data columns in csv file. I want to create 50 arrays and each array will store data as I proceed to read and parse the file line by line. I want to store the 50 arrays in variable names same as the column name read the header line.

Upvotes: 0

Views: 3147

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 113988

data = csv.reader(open("my_text.csv"))
columns = zip(*data)
dataMap = {d[0]:d[1:] for d in columns}
print dataMap["Timestamp"] # or whatever

is a much preferred method ... if you really want variable names try

globals().update({d[0]:d[1:] for d in columns})
print Timestamp # or whatever

but I strongly advise against this

really what it sounds like you want is pandas.DataFrame.from_csv though

df = pandas.DataFrame.from_csv("data.txt")

print df["Timestamp"] # or whatever your header names might be

Upvotes: 2

Related Questions