【问题标题】:Count of elements in lists within pandas data frame熊猫数据框中列表中的元素计数
【发布时间】:2018-02-09 13:36:23
【问题描述】:

当列表在熊猫数据框列中时,我需要获取列表中每个元素的频率

在数据中:

din=pd.DataFrame({'x':[['a','b','c'],['a','e','d', 'c']]})`

              x
0     [a, b, c]
1  [a, e, d, c]

期望的输出:

   f  x
0  2  a
1  1  b
2  2  c
3  1  d
4  1  e

我可以将列表扩展为行,然后执行分组,但这些数据可能很大(超过百万条记录),我想知道是否有更有效/更直接的方法。

谢谢

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    首先是lists 的flatten 值,然后按value_countssizeCounter 计数:

    a = pd.Series([item for sublist in din.x for item in sublist])
    

    或者:

    a = pd.Series(np.concatenate(din.x))
    

    df = a.value_counts().sort_index().rename_axis('x').reset_index(name='f')
    

    或者:

    df = a.groupby(a).size().rename_axis('x').reset_index(name='f')
    

    from collections import Counter
    from  itertools import chain
    
    df = pd.Series(Counter(chain(*din.x))).sort_index().rename_axis('x').reset_index(name='f')
    
    print (df)
       x  f
    0  a  2
    1  b  1
    2  c  2
    3  d  1
    4  e  1
    

    【讨论】:

    • 完美!运行时间对我来说几乎都花费了相同的时间,但我还是使用了Counter。谢谢
    【解决方案2】:

    你也可以有一个这样的衬里:

    df = pd.Series(sum([item for item in din.x], [])).value_counts()
    

    【讨论】:

      【解决方案3】:

      使用扁平列表和计数器实际上很容易

      from matplotlib.cbook import flatten
      from collections import Counter
      
      din={'x':[['a','b','c'],['a','e','d', 'c']]}
      for a,i in din.items() :
          u=pd.DataFrame.from_dict(dict(Counter([*flatten(i)])), orient ='index').reset_index().rename(columns ={'index':a,0:str(a)+'_number'})
      

      输出:

      但是,如果 din 有多个键和值,您将需要一个函数来执行相同的操作

      from matplotlib.cbook import flatten
      from collections import Counter
      din={'x':[['a','b','c'],['a','e','d', 'c']], 'y': [['h','j'],['h','j','j']]}
      
      def foo(x):
          df = pd.DataFrame()
          for a,i in x.items() :
              u=pd.DataFrame.from_dict(dict(Counter([*flatten(i)])), orient ='index').reset_index().rename(columns ={'index':a,0:str(a)+'_number'})
              df=pd.concat([df,u])
          return df
      foo(din)
      

      【讨论】:

        【解决方案4】:

        我会使用 pandas 的 explodevalue_counts 然后最后将其分配给一个框架。

        din.explode('x').value_counts().to_frame('fq').reset_index().sort_values('x')
           x  fq
        0  a   2
        2  b   1
        1  c   2
        3  d   1
        4  e   1
        

        【讨论】:

          猜你喜欢
          • 2018-10-23
          • 2019-12-02
          • 2019-05-22
          • 2019-02-14
          • 2023-02-01
          • 2023-01-19
          • 2020-10-29
          • 1970-01-01
          相关资源
          最近更新 更多