Need to pivot pandas dataframe

Question:

I downloaded a csv from the world bank website that has stats for Australia going back to 1960(https://data.worldbank.org/country/australia) . I have read the csv in to a pandas dataframe but after removing unnecessary rows and columns it has the years as columns and the stat fields as rows:

# Load the data
df = pd.read_csv('Aus_stats.csv', header=2)
rate = pd.read_csv('AUDUSD historical rate from 1960.csv')

# Data Munging
# years = range(1960, 2022, 1)
df.drop(df.columns[[0,1,2]], axis = 1, inplace = True)
df

Output from df

When I try and pivot the table to have the years as the index (as I am trying to get to) then I end up with the following:

df = df.pivot(columns = 'Indicator Code', index = ['1960'])
df

Output after pivot

Ideally I want to see each stat indicator as the column headers and have the years (1960-2022) as the index for the rows

Asked By: adamc

||

Answers:

Try:

df.set_index("Indicator Code").transpose()
Answered By: Xukrao
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.