【问题标题】:Create a pandas dataframe of counts创建计数的熊猫数据框
【发布时间】:2015-06-26 15:12:40
【问题描述】:

我想创建一个包含两列的 pandas 数据框,第一列是我的一个列的唯一值,第二列是唯一值的计数。

我看过很多帖子(例如here)描述如何获取计数,但我遇到的问题是当我尝试创建数据框时,列值成为我的索引。

样本数据:df = pd.DataFrame({'Color': ['Red', 'Red', 'Blue'], 'State': ['MA', 'PA', 'PA']})。我想得到一个像这样的数据框:

   Color Count
0   Red  2
1  Blue  1

我尝试了以下方法,但在所有情况下,索引都以 Color 结尾,而 Count 是数据框中的唯一列。

尝试 1:

df2 = pd.DataFrame(data=df['Color'].value_counts())
# And resetting the index just gets rid of Color, which I want to keep
df2 = df2.reset_index(drop=True)

尝试 2:

df3 = df['Color'].value_counts()
df3 = pd.DataFrame(data=df3, index=range(df3.shape[0]))

尝试 3:

df4 = df.groupby('Color')
df4 = pd.DataFrame(df4['Color'].count())

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    另一种方法,使用value_counts

    In [10]: df = pd.DataFrame({'Color': ['Red', 'Red', 'Blue'], 'State': ['MA', 'PA', 'PA']})
    
    In [11]: df.Color.value_counts().reset_index().rename(
               columns={'index': 'Color', 0: 'count'})
    Out[11]:
      Color  count
    0   Red      2
    1  Blue      1
    

    【讨论】:

      【解决方案2】:

      本质上等同于设置列名,但改用rename方法:

      df.groupby('Color').count().reset_index().rename(columns={'State': 'Count'})
      

      【讨论】:

      • 我注意到这种方法的一个小问题:如果有两个以上的列,那么所有额外的列也会得到计数。
      • 这取决于你想看到什么。假设有两行颜色=红色,那么对于每一列,该行的颜色=红色有两个值。您总是可以只明确选择一列。
      【解决方案3】:

      一种可读的解决方案是使用to_framerename_axis 方法:

      res = df['Color'].value_counts()\
                       .to_frame('count').rename_axis('Color')\
                       .reset_index()
      
      print(res)
      
        Color  count
      0   Red      2
      1  Blue      1
      

      【讨论】:

        【解决方案4】:
        df = df.groupby('Color').count().reset_index()
        df.columns = ['Color','Count']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-01-13
          • 2021-06-02
          • 2023-02-01
          • 2018-11-04
          • 1970-01-01
          • 2014-11-22
          • 1970-01-01
          相关资源
          最近更新 更多