python equivalent of R table

前端 未结 7 1732
没有蜡笔的小新
没有蜡笔的小新 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:15

    In Numpy, the best way I've found of doing this is to use unique, e.g:

    import numpy as np
    
    # OPs data
    arr = np.array([[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]])
    
    values, counts = np.unique(arr, axis=0, return_counts=True)
    
    # into a dict for presentation
    {tuple(a):b for a,b in zip(values, counts)}
    

    giving me: {(0, 6): 19, (6, 0): 20, (12, 0): 33, (12, 6): 28} which matches the other answers

    This example is a bit more complicated than I normally see, and hence the need for the axis=0 option, if you just want unique values everywhere, you can just miss that out:

    # generate random values
    x = np.random.negative_binomial(10, 10/(6+10), 100000)
    
    # get table
    values, counts = np.unique(x, return_counts=True)
    
    # plot
    import matplotlib.pyplot as plt
    plt.vlines(values, 0, counts, lw=2)
    

    R seems to make this sort of thing much more convenient! The above Python code is just plot(table(rnbinom(100000, 10, mu=6))).

提交回复
热议问题