Create dynamic columns in dataframe using pandas

前端 未结 2 2068
-上瘾入骨i
-上瘾入骨i 2021-01-24 07:27

How to create dynamic columns from this pandas dataframe.

 Name, Sex
    a, M
    b, F
    c, M
    d, F

Expected dataframe:

Na         


        
2条回答
  •  礼貌的吻别
    2021-01-24 08:08

    You can create a count variable based on the two columns and then do the pivoting, something like:

    import pandas as pd
    df.groupby(["Name", "Sex"]).size().unstack(level = 1, fill_value = 0)
    
    # Sex   F   M
    #Name       
    #   a   0   1
    #   b   1   0
    #   c   0   1
    #   d   1   0
    

    Another option is to use crosstab from pandas:

    import pandas as pd
    pd.crosstab(df['Name'], df['Sex'])
    
    # Sex   F   M
    #Name       
    #   a   0   1
    #   b   1   0
    #   c   0   1
    #  d    1   0
    

提交回复
热议问题