How would I extend a Pandas DataFrame such as this?

Let’s say I have the following DataFrame from Pandas:

import pandas as pd
inp = [{'age 15-19':10, 'age 20-30':100, 'Gender': 'F'}, {'age 15-19':11,'age 20-30':110, 'Gender': 'M'}, {'age 15-19':12,'age 20-30':120, 'Gender': 'F'}]
df = pd.DataFrame(inp)
print(df)

Output:

       age_15-19   age_20-30    Gender
0         10          100         F
1         11          110         M
2         12          120         F 

And I’d like to turn it into a different table such as this:

          Age       Gender    Number
0         15-19       F         10
1         15-19       M         11
2         15-19       F         12
3         20-30       F         100
4         20-30       M         110
5         20-30       F         120

But I have no idea how to code it. Is that possible on Pandas? How would I proceed? I’m still a rookie in Python and Programming in general.

Answer

Use melt

pd.melt(df, id_vars=['Gender'], value_vars=['age 15-19','age 20-30'], var_name='Age', value_name='Number')

Output

    Gender  Age Number
0   F   age 15-19   10
1   M   age 15-19   11
2   F   age 15-19   12
3   F   age 20-30   100
4   M   age 20-30   110
5   F   age 20-30   120