1

I'm trying to take the column headers of a table in an ASCII file. With these column headers I want to then loop through them and use them in a function to create individual graphs based on their data below.

I have the graphical side of things all done as it has been done manually typing out each different column but I want to condense the data down.

The column headers will range from around 4-30 columns.

I'm assuming I'll need to be able to iterate through them in form of for i in headers: If anyone could shed light on how to get the headers on their own so I can reference them I'd be grateful

Oli

OParker
  • 265
  • 1
  • 5
  • 19

1 Answers1

0

Just pass nrows=1 and then get the columns:

pd.read_csv(file_path, nrows=1).columns

Example:

In [83]:
import io
import pandas as pd
t="""index,col1,col2,col3
0,1,2,3"""
pd.read_csv(io.StringIO(t), nrows=1).columns

Out[83]:
Index(['index', 'col1', 'col2', 'col3'], dtype='object')

You can ignore the io bit, and you may need to modify the read_csv params depending on your file path and separator character

EdChum
  • 376,765
  • 198
  • 813
  • 562
  • Thank you very much Ed it's worked perfectly. Apologies it's probably a very basic question but I'm fairly new to this whole thing. I used `headers1 = pd.read_csv(file1, nrows=1).columns` If I want to then iterate through these do I reference something like `for i in headers1:` – OParker Sep 10 '15 at 09:03
  • Ah that's what that tick is for! (New to SO as well!). Thank you for your help Ed! – OParker Sep 10 '15 at 09:11
  • Actually Ed I've just noticed that before every column the letter u has appeared... any ideas how to get rid of this? `Index([u'tLap', u'sLap', u'NLap', u'vCar',` – OParker Sep 10 '15 at 09:13
  • 1
    It's marking the strings as unicode see [related](http://stackoverflow.com/questions/599625/python-string-prints-as-ustring) – EdChum Sep 10 '15 at 09:22
  • Ed I don't know if you'll see or get a notification for this but I could really do with your help on another problem. I must have posted at a bad time and it's now buried under a lot of other posts. http://stackoverflow.com/q/32606488/5313069 If there's any chance you could advise you were very helpful on this one! – OParker Sep 16 '15 at 12:40
  • (Sorry didn't know I could tag) @EdChum – OParker Sep 16 '15 at 13:30