3

I have the foll. text file:

line_1
line_2
line_3
Col_A    Col_B   Col_C
1.2      33       45
23       12       55

Here is how I read it:

df  = pandas.read_table(file_name, skiprows=3, sep=' ', skipinitialspace=True)

Is there any way I can access just the header row?i.e. 'Col_A Col_B Col_C' as a string? I do not want to use df.columns.values since it returns an array. I want to get the header row with the spacing between different columns preserved.

1
  • do you mean df.columns.str.join(' ') or ' '.join(df.columns) if you want a str Commented Oct 18, 2015 at 22:13

1 Answer 1

2

You can just do:

In [6]:
' '.join(df)

Out[6]:
'Col_A Col_B Col_C'

This works because the iterable returned from a df are the columns which are strings so you can just join them with your separator.

EDIT

If you want to get exactly what your header was stored then you can do the following:

In [8]:
df = pd.read_table(io.StringIO(t), skiprows=3, header=None, nrows=1)
df

Out[8]:
                        0
0  Col_A    Col_B   Col_C

In [10]:
df.iloc[0][0]

Out[10]:
'Col_A    Col_B   Col_C'

So this doesn't specify a separator so it will look for commas which there are none so the entire header row is read as a single column value, you can then get just the row value by indexing it as shown above

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

5 Comments

sorry, I should have been clearer. I want to preserve the number of spaces between Col_A, Col_B and Col_C. Using ' '.join does not preserve that
@user308827 When you add the header rows to a dataframe, are the sapces preserved in each coloum? What is the delimeter of the dataframe?? Is it delimeted by spaces?
Since you read your csv in and specified the separator then you lose the original spaces you could do it using this: df = pandas.read_table(file_name, skiprows=3, header=None, nrows=1) this wlll create a single row df with just your header as the data row, you can then just do df.iloc[0][0] to get the header as a string
@pelumi, the delimiter is spaces. Not sure if spaces are preserved though
Yes you can ignore that bit, it's just for me to load your data

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.