3

I have a small question about pandas dataframe. How can I pivot my dataframe from this

AGE       | GROUP-A | ... | GROUP-Q 
----------|---------|-----|---------
00-04     |77       |     |133
05-17     |117      |     |106
18-25     |64       |     |110

to this

GROUP | 00-04 | 05-17 | 18-25 
------|-------|-------|-------
A     |77     |117    |64
...   |       |       | 
Q     |133    |106    |110
6
  • Sorry I don't get - is it a single line including both column names and values that you want to convert to a table with column names int the first row, and values in the following rows? Commented May 9, 2018 at 10:05
  • Sorry I don't know why i can't put it in a tabular form. I'm trying to resolve the problem. Commented May 9, 2018 at 10:08
  • Can you post say 3 rows of your original text, and 3 rows of how you would like the output to look like? That may help understanding better what you need? Commented May 9, 2018 at 10:09
  • is it better ike this ? Commented May 9, 2018 at 10:23
  • I don't think you are after a pivot table. I think what you really want to do is df.transpose(). You will need to then do some more work to change the column/row names as you have them in the question. The answer here may help you with that. Commented May 9, 2018 at 10:39

2 Answers 2

3

You can achieve your desired result by setting 'AGE' as your index, followed by pd.DataFrame.transpose:

df = pd.DataFrame({'AGE': ['00-04', '05-17', '18-25'],
                   'GROUP-A': [77, 117, 64],
                   'GROUP-Q': [133, 106, 110]})

res = df.set_index('AGE')\
        .transpose()

print(res)

AGE      00-04  05-17  18-25
GROUP-A     77    117     64
GROUP-Q    133    106    110
Sign up to request clarification or add additional context in comments.

Comments

0

Using @JPP setup, you can use the following to get your exact expected output in your question.

df.set_index('AGE').rename(columns=lambda x: x[-1])\
  .T.rename_axis('GROUP').rename_axis([None], axis=1)\
  .reset_index()

Output:

  GROUP  00-04  05-17  18-25
0     A     77    117     64
1     Q    133    106    110

Note: .T is the same as .transpose, just easier to type.

Comments

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.