0

I saw a lot of examples transposing the data but not something similar. I am trying to transpose my csv data which looks like--

Region,1989,1900,2000
new york,3,4,5
atlanta,7,9,0
chicago,8,9,10

to

Region,Year,value
new york,1989,3
new york,1900,4
new york,2000,5
atlanta,1989,7
atlanta,1900,9
atlanta,2000,0
jpp
  • 159,742
  • 34
  • 281
  • 339
user435215
  • 127
  • 2
  • 11

1 Answers1

0

You are trying to convert from wide data format to long data format. This can be done using melt function. If you have some columns that needs to be eliminated, you can slice the dataframe to the columns of interest.

Code:

#creating df
df = pd.DataFrame(data = {'Region':['new york', 'atlanta', 'chicago'], '1989': [3,7,8], '1900': [4,9,9], '2000': [5,0,10]})

#converting to long format
long_df = pd.melt(df, id_vars=['Region'], value_vars=['1989', '1900', '2000'], var_name='year', value_name = 'value')

Output:

enter image description here

Naveen
  • 1,190
  • 7
  • 20