【问题标题】:counting column values in pandas计算熊猫中的列值
【发布时间】:2015-03-09 00:25:09
【问题描述】:
dictionary = {'Year': [1985, 1985, 1986, 1986, 1987, 1987, 1987]}
pdf = pd.DataFrame(dictionary)

    Year
0   1985
1   1985
2   1986
3   1986
4   1987
5   1987
6   1987

我有一个名为 pdf 的数据框,我需要按以下格式形成一个 new data frame

Year   count
1985     2
1986     2 
1987     3

如何在 pandas 中有效地做到这一点?

【问题讨论】:

    标签: python python-2.7 pandas


    【解决方案1】:

    .value_counts

    pdf['Year'].value_counts()
    

    【讨论】:

      【解决方案2】:

      答案如下:

      dictionary = {'Year': [1985, 1985, 1986, 1986, 1987, 1987, 1987]}
      pdf = pd.DataFrame(dictionary)
      gb = pdf.groupby('Year')['Year'].count()
      

      【讨论】:

        【解决方案3】:

        Counter 是一个计数器工具,用于支持方便快速地统计字典和其他可散列对象。

        from collections import Counter
        
        df = pd.DataFrame(Counter(pd.DataFrame(dictionary).Year).items(), 
                          columns=['Year', 'Count'])
        
        >>> print df
        print(df)
           Year  Count
        0  1985      2
        1  1986      2
        2  1987      3
        
        %timeit pd.DataFrame(dictionary).groupby('Year')['Year'].count()
        1000 loops, best of 3: 777 µs per loop
        
        %timeit pd.DataFrame(Counter(pd.DataFrame(dictionary).Year).items(), columns=['Year', 'Count'])
        1000 loops, best of 3: 672 µs per loop
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-03-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-01
          相关资源
          最近更新 更多