【问题标题】:How to count the frequency of two columns in numpy array?如何计算numpy数组中两列的频率?
【发布时间】:2018-04-04 06:47:09
【问题描述】:
In [56]: df
Out[56]:
array([[3, 133, nan, ..., 202, 109, 1427],
       [3, 133, nan, ..., 183, 120, 1448],
       [3, 133, nan, ..., 205, 22, 417],
       ...,
       [8, 43, nan, ..., 88, 11, 11],
       [64, 173, nan, ..., 2774, 2029, 1210],
       [12, 85, nan, ..., 19, 10, 25]], dtype=object)
collections.Counter(df[:,[0,1]])

df 是 numpy 数组,我想获取第一列和第二列的计数,就像 count(*) from df group by col-0, col-1 但是返回错误TypeError: unhashable type: 'numpy.ndarray' 我怎样才能意识到它?

Pandas 很慢,我不习惯用它。

【问题讨论】:

  • 添加样例?
  • .. 和预期的输出。一个最小的可重现样本情况会更好。

标签: python arrays pandas numpy


【解决方案1】:

collection.Counter 用于计算可散列对象,而 'numpy.ndarray' 是不可散列的,因此我们需要将其转换为可散列对象。例如,

>>> a = np.array([  [1, 2, 3],
        [1, 4, 5],
        [5, 6, 7],
        [8, 9, 10]])
>>> b = np.hsplit(a,3)[0]
>>> b
array([[1],
   [1],
   [5],
   [8]])
>>> c = b.flatten().tolist()
>>> c
[1, 1, 5, 8]
>>> collections.Counter(c)
>>> c
Counter({1: 2, 8: 1, 5: 1})

希望这会有所帮助。

【讨论】:

    【解决方案2】:
    a = np.array([[4, 3, 2],
                  [1, 0, 3],
                  [1, 2, 3],
                  [0, 1, 4],
                  [0, 3, 3],
                  [0, 2, 0],
                  [1, 4, 3],
                  [4, 1, 2],
                  [0, 1, 3],
                  [2, 1, 0]])
    

    numpy方式:

    In [8]: np.apply_along_axis(np.bincount, 0, a)
    Out[8]: 
    array([[4, 1, 2],
           [3, 4, 0],
           [1, 2, 2],
           [0, 2, 5],
           [2, 1, 1]])
    

    熊猫

    df = pd.DataFrame(a)
    
    In [10]: df[0].value_counts()
    Out[10]: 
    0    4
    1    3
    4    2
    2    1
    

    如果你想同时多列:

    In [11]: df.apply(pd.Series.value_counts, axis=0)
    Out[11]: 
         0  1    2
    0  4.0  1  2.0
    1  3.0  4  NaN
    2  1.0  2  2.0
    3  NaN  2  5.0
    4  2.0  1  1.0
    

    你也可以摆脱NaNs

    In [12]: df.apply(pd.Series.value_counts, axis=0).fillna(0)
    Out[12]: 
         0  1    2
    0  4.0  1  2.0
    1  3.0  4  0.0
    2  1.0  2  2.0
    3  0.0  2  5.0
    4  2.0  1  1.0
    

    【讨论】:

      【解决方案3】:

      由于您使用的是numpy,因此您可以为此使用numpy.unique

      a = np.array([  [1, 2, 3],
                      [1, 4, 5],
                      [5, 6, 7],
                      [8, 9, 10]])
      
      res = np.unique(a[:, :3], return_counts=True)
      # (array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10]), array([2, 1, 1, 1, 2, 1, 1, 1, 1, 1], dtype=int64))
      
      res_dict = dict(zip(*res))
      # {1: 2, 2: 1, 3: 1, 4: 1, 5: 2, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1}
      

      【讨论】:

        猜你喜欢
        • 2019-09-12
        • 2019-05-03
        • 1970-01-01
        • 2017-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-08
        • 1970-01-01
        相关资源
        最近更新 更多