Search code examples
pythonreformatting

Reformatting a table based on duplicates in python


I have a table with three columns as follows:

time  variable  value
t1    var1      x1
t1    var2      x2
t2    var1      x3
t2    var2      x4
t3    var1      x5
t3    var2      x6

I want to reformat this table in such a way as to have unique time instants and to get the values of each variable at that instant as follows:

time  var1  var2
t1    x1    x2
t2    x3    x4
t3    x5    x6

I'm using Spyder IDE.


Solution

  • it is easier to use a dataframes from pandas library and you can solve it using the pandas pivot method as follows

    df = pd.load_csv("yourfilename.csv")
    df.pivot(index='time', columns='variable', values='value')