0

Python: How can I make column values as column headers
Problem:

Question

Possible solution (Index NOC)

enter image description here

Senne
  • 31
  • 5
  • Paste your dataframe in a way it is immediately usable in Python please. – TheConfax Jan 12 '22 at 22:52
  • Also, please spend a few minutes researching your question... – Mad Physicist Jan 12 '22 at 22:55
  • @MadPhysicist Did the research, found some possible solutions online. But I am not able to solve this. I am still a student and learning the basics of data science. I am stuck at this problem for a couple of hours already ;( (https://stackoverflow.com/questions/47152691/how-can-i-pivot-a-dataframe) – Senne Jan 12 '22 at 23:03
  • @TheConfax How I am able to do this? I exported a csv from the Dataframe but I am not able to post this on stackoverflow. Is there another possbile solution to share a dataframe? – Senne Jan 12 '22 at 23:04
  • Check out [ask] before posting. It will tell you the required information and hopefully explain the down and close vote. Please read it with the understanding that everyone here is a volunteer and you are not entitled to their time. – Mad Physicist Jan 12 '22 at 23:18

1 Answers1

0

I believe pivot is what you are looking for.

raw_data = {'NOC': ['USA', 'USA', 'USA', 'RUS', 'RUS', 'RUS', 'CHN'], 
            'medal': ['Gold', 'Silver', 'Bronze', 'Gold', 'Silver', 'Bronze', 'Gold'], 
            'Aantal': ['500', '400', '300', '200', '100', '250', '330']}
df = pd.DataFrame(raw_data)
cont_tab = df.pivot(index='NOC', columns='medal')
cont_tab = cont_tab.fillna(0)
print(cont_tab)

This is the output:

      Aantal            
medal Bronze Gold Silver
NOC                     
CHN        0  330      0
RUS      250  200    100
USA      300  500    400

Check out this example for more info.

sansh
  • 41
  • 3