【问题标题】:Query DataFrame, count values and return features and counts as DataFrame [duplicate]查询DataFrame,计数值并返回特征和计数为DataFrame [重复]
【发布时间】:2021-09-22 01:26:23
【问题描述】:

我有一个pandas DataFrame,需要做以下事情:查询DateFrame,计算一列中的值出现的次数并返回另一个DataFrame,其中第一列是特征名称,第二列是数量计数。我可以将一系列结果返回到 DataFrame,但它只给出一列。

见下文。

df_1 = pd.DataFrame({'id': ['001', '002', '003', '004', '005', '006', '007', '008'],
                     'color_value': ['blue', 'red', 'yellow', 'orange',
                     'blue','red', 'blue', 'orange']})

df_1=

id   color_value
001  blue
002  red
003  yellow
004  orange
005  blue
006  red
007  blue
008  orange

num_counts = df_1['color_value'].value_counts()

num_counts =
blue      3
orange    2
red       2
yellow    1
Name: color_value, dtype: int64

# convert from a series to DataFrame
num_counts.to_frame()

        color_value
blue    3
orange  2
red     2
yellow  1

我需要将上面的 1 列 DataFrame 转换为 2 列 DataFrame,其中第 1 列标题 = 特征,第 2 列标题 = 计数。我无法手动执行此操作,因为实际矩阵非常大。目标是拥有一些我可以绘制计数的东西,以查看所有特征的计数分布。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    只需使用reset_index:

    >>> df_1['color_value'].value_counts().reset_index()
        index  color_value
    0    blue            3
    1  orange            2
    2     red            2
    3  yellow            1
    >>> 
    

    如果您关心列名:

    >>> df_1['color_value'].value_counts().rename_axis('color_value').reset_index(name='count')
      color_value  count
    0        blue      3
    1      orange      2
    2         red      2
    3      yellow      1
    >>> 
    

    【讨论】:

      猜你喜欢
      • 2019-08-11
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多