python equivalent of R table

前端 未结 7 1590
没有蜡笔的小新
没有蜡笔的小新 2021-01-30 19:27

I have a list

[[12, 6], [12, 0], [0, 6], [12, 0], [12, 0], [6, 0], [12, 6], [0, 6], [12, 0], [0, 6], [0, 6], [12, 0], [0, 6], [6, 0], [6, 0], [12, 0], [6, 0], [         


        
7条回答
  •  一向
    一向 (楼主)
    2021-01-30 20:23

    Supposing you need to convert the data to a pandas DataFrame anyway, so that you have

    L = [[12, 6], [12, 0], [0, 6], [12, 0], [12, 0], [6, 0], [12, 6], [0, 6], [12, 0], [0, 6], [0, 6], [12, 0], [0, 6], [6, 0], [6, 0], [12, 0], [6, 0], [12, 0], [12, 0], [0, 6], [0, 6], [12, 6], [6, 0], [6, 0], [12, 6], [12, 0], [12, 0], [0, 6], [6, 0], [12, 6], [12, 6], [12, 6], [12, 0], [12, 0], [12, 0], [12, 0], [12, 6], [12, 0], [12, 0], [12, 6], [0, 6], [0, 6], [6, 0], [12, 6], [12, 6], [12, 6], [12, 6], [12, 6], [12, 0], [0, 6], [6, 0], [12, 0], [0, 6], [12, 6], [12, 6], [0, 6], [12, 0], [6, 0], [6, 0], [12, 6], [12, 0], [0, 6], [12, 0], [12, 0], [12, 0], [6, 0], [12, 6], [12, 6], [12, 6], [12, 6], [0, 6], [12, 0], [12, 6], [0, 6], [0, 6], [12, 0], [0, 6], [12, 6], [6, 0], [12, 6], [12, 6], [12, 0], [12, 0], [12, 6], [0, 6], [6, 0], [12, 0], [6, 0], [12, 0], [12, 0], [12, 6], [12, 0], [6, 0], [12, 6], [6, 0], [12, 0], [6, 0], [12, 0], [6, 0], [6, 0]]
    df = pd.DataFrame(L, columns=('a', 'b'))
    

    then you can do as suggested in this answer, using groupby.size():

    tab = df.groupby(['a', 'b']).size()
    

    tab looks as follows:

    In [5]: tab
    Out[5]:
    a   b
    0   6    19
    6   0    20
    12  0    33
        6    28
    dtype: int64
    

    and can easily be changed to a table form with unstack():

    In [6]: tab.unstack()
    Out[6]:
    b      0     6
    a
    0    NaN  19.0
    6   20.0   NaN
    12  33.0  28.0
    

    Fill NaNs and convert to int at your own leisure!

提交回复
热议问题