1
$\begingroup$

Hi I'm new to data science. Learning data science from course-era. I'm having pandas data frame as follows,

   time   value

A   9      5
A   8      4
A   7      3
B   9      3
B   8      2
B   7      1
C   9      3
C   8      2
C   7      1

I want to convert this as ,

       A   B  C

9      5   3  3 
8      4   2  2
7      3   1  1

As I start to write query for this, it is getting complicated. Is there any easy way to do this? Thanks for the help.

$\endgroup$

2 Answers 2

1
$\begingroup$

For me, when it comes to reshaping a dataframe(switching columns/indices/rows and such) its fairly intuitive using the pivot_table function.

my_df.pivot_table(index='time', columns=my_df.index, values='value')
$\endgroup$
0
0
$\begingroup$

Recreating your problem:

import pandas as pd
d={'time':[9, 8, 7, 9, 8, 7, 9, 8, 7],'value':[5, 4, 3, 3, 2, 1, 3, 2, 1]}
df = pd.DataFrame(data=d,index=['A', 'A', 'A', 'B','B','B','C','C','C'])

Using a function with for loop.

def change_my_df(give_df,column_to_index,value_in_cell):
"""Specify the dataframe, the column that will become the new inex, the column that will populate the cell of the new df"""
    new_index=give_df[column_to_index].unique().tolist()
    new_columns=list(set(give_df.index.values))
    new_df=pd.DataFrame(index=new_index,columns=new_columns)
    for l,r in give_df.iterrows():
        new_df[l][r[str(column_to_index)]]=r[str(value_in_cell)]
    return new_df
new_df=change_my_df(df,'time','value')
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.