Need to do the operation inverse of the link. How to duplicate the country for each year in python? , that is, from the columns in the second screenshot, make the lines as in the first?

    1 answer 1

    Source DataFrame:

    In [18]: df = pd.DataFrame(np.random.randint(0,5,(10,3)), columns=list('abc')) In [19]: df Out[19]: abc 0 3 3 3 1 1 1 4 2 2 0 1 3 2 0 1 4 0 3 0 5 3 0 0 6 4 0 1 7 4 4 2 8 4 4 4 9 1 1 2 

    Now we will make from the values ​​of the column a - the index, from b - the columns, c - the values ​​(duplicates will be added up)

    pivot_table () method:

     In [20]: df.pivot_table(index='a', columns='b', values='c', aggfunc='sum', fill_value=0) Out[20]: b 0 1 3 4 a 0 0 0 0 0 1 0 6 0 0 2 2 0 0 0 3 0 0 3 0 4 1 0 0 6 

    groupby () + aggregate function + unstack () :

     In [21]: df.groupby(['a','b']).sum().unstack('b', fill_value=0) Out[21]: c b 0 1 3 4 a 0 0 0 0 0 1 0 6 0 0 2 2 0 0 0 3 0 0 3 0 4 1 0 0 6