代码之家  ›  专栏  ›  技术社区  ›  blue-sky

计算“熊猫”列中每个值出现的次数

  •  2
  • blue-sky  · 技术社区  · 6 年前
    import pandas as pd 
    
    test_values = []
    
    test_values.append(np.array([1,0,1]))
    test_values.append(np.array([1,0,1]))
    test_values.append(np.array([0,1,1]))
    
    test_values
    
    df = pd.DataFrame(test_values)
    

    呈现此数据帧会产生:

       0  1  2
    0  1  0  1
    1  1  0  1
    2  0  1  1
    

    我正试图计算每个值在列中出现的次数,因此对于上面的数据帧,应该生成以下内容:

    1 occurs 2, 0 occurs 0. 
    0 occurs 2, 1 occurs 1. 
    1 occurs 3, 0 occurs 0.
    

    使用.values():

    for i in range(0 , df.shape[1]) : 
        print(df.iloc[:,i].value_counts().values)
    

    生产:

    [2 1]
    [2 1]
    [3]
    

    标签已从每列中删除。如何访问每个计数的相关标签?因此可以产生:

    1发生2,0发生0。
    0发生在2,1发生在1。
    1发生3,0发生0。
    
    3 回复  |  直到 6 年前
        1
  •  2
  •   cors    6 年前

    简单解决方案:

    df.apply(pd.Series.value_counts)
    
        2
  •  2
  •   jezrael    6 年前

    如果只有预期 0 1 值添加 reindex 对于添加缺少的值-按预期值列表重新索引:

    for i in range(0 , df.shape[1]) : 
        a = df.iloc[:,i].value_counts().reindex([0,1], fill_value=0)
        print (', '.join('{} occurs {}.'.format(k, v) for k, v in a.items()))
    
    0 occurs 1., 1 occurs 2.
    0 occurs 2., 1 occurs 1.
    0 occurs 0., 1 occurs 3.
    
        3
  •  2
  •   jpp    6 年前

    您可以通过 pd.Series.items :

    for i in range(0 , df.shape[1]):
        counts = df.iloc[:,i].value_counts()
        gen = (f'{key} occurs {value} times' for key, value in counts.items())
        print(*gen, sep=', ')
    

    不清楚您希望如何推断零计数,所以我没有假设这是一个要求。结果给出:

    1 occurs 2 times, 0 occurs 1 times
    0 occurs 2 times, 1 occurs 1 times
    1 occurs 3 times