-2

I have found the dataset:

Dataset

I want to transform it in order to appear exactly like:

Second Dataset

My main problem is how to put the row header as values in a column named years. Any thoughts or any ideas?

Henry Ecker
  • 31,792
  • 14
  • 29
  • 50
Mry
  • 1
  • 1
  • 2
    Please add your code. I am not sure what you would like us to help you with –  Jun 01 '21 at 01:33
  • 2
    Welcome to Stack Overflow! Please include any relevant information [as text directly into your question](https://stackoverflow.com/editing-help), do not link or embed external images of source code or data. Images make it difficult to efficiently assist you as they cannot be copied and offer poor usability as they cannot be searched. See: [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/q/285551/15497888) – Henry Ecker Jun 01 '21 at 01:34
  • 1
    If you need assistance formatting a small sample of your DataFrame as a copyable piece of code for SO see [How to make good reproducible pandas examples](https://stackoverflow.com/q/20109391/15497888). – Henry Ecker Jun 01 '21 at 01:34
  • All that said it looks like [DataFrame.melt](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.melt.html#pandas-dataframe-melt) – Henry Ecker Jun 01 '21 at 01:37
  • Did my answer help... or not? –  Jun 01 '21 at 05:12
  • solve it with the melt command. Thank you – Mry Jun 02 '21 at 00:24

1 Answers1

0

I am going to assume that your dataset, is a CSV file, I would do the following:

import csv
from operator import itemgetter

with open('name.csv', 'key') as f:
    data = [line for line in csv.reader(f)]

newRecord = [Entity, Code, Year, Prevelance of Obesity]
data.append(newRecord)

data.sort(key=itemgetter(1))  # 1 being the column number

with open('name.csv', 'w') as f:
    csv.writer(f).writerows(data)
  • Yes, it is a CSV file. ValueError: invalid mode: 'key' when I use the third line, without the "key" I have the error in the line with the "w" that [Errno 13] Permission denied: and without the "w" the CSV is not writable – Mry Jun 02 '21 at 00:17
  • solve it with the melt command. Thank you – Mry Jun 02 '21 at 00:24
  • The 'key' is what you're looking for, like "City" or "AFG" get it? –  Jun 02 '21 at 02:20