【发布时间】: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 列标题 = 计数。我无法手动执行此操作,因为实际矩阵非常大。目标是拥有一些我可以绘制计数的东西,以查看所有特征的计数分布。
【问题讨论】: