2

I read an xlsx file with two headers into a panda dataframe. Now I fail to select a row according to header 1 or two.

Googeling my probelm did not bring up an answer which worked, so I try it here

My Excel looks like this:

Here you see an excerpt of the test excel:

enter image description here Now I read the excel file into pandas like this:

df = pd.read_excel('XLsample.xlsx', sheet_name=0, header=[0,1], index_col=0)

How can I read a column dependent on header 0 or 1 ? I mean something like this:

persons = df[header[1]]['Name']

numbers = df[header[0]]['int']

thx for your support

1 Answer 1

3

Use DataFrame.xs:

persons = df.xs('Name', axis=1, level=1)

numbers = df.xs('int', axis=1, level=0)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! That is what I was looking for!

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.