Change column values to column headers in pandas

后端 未结 1 477
别跟我提以往
别跟我提以往 2020-12-09 05:24

I have the following code, which takes the values in one column of a pandas dataframe and makes them the columns of a new data frame. The values in the first column of the d

相关标签:
1条回答
  • 2020-12-09 06:30

    This looks like a job for pivot:

    import pandas as pd
    oldcols = {'col1':['a','a','b','b'], 'col2':['c','d','c','d'], 'col3':[1,2,3,4]}
    a = pd.DataFrame(oldcols)  
    
    newf = a.pivot(index='col1', columns='col2')
    print(newf)
    

    yields

          col3   
    col2     c  d
    col1         
    a        1  2
    b        3  4
    

    If you don't want a MultiIndex column, you can drop the col3 using:

    newf.columns = newf.columns.droplevel(0)
    

    which would then yield

    col2  c  d
    col1      
    a     1  2
    b     3  4
    
    0 讨论(0)
提交回复
热议问题