【发布时间】:2018-11-25 12:14:18
【问题描述】:
我在 Pandas DataFrame 中按两列分组,然后计算每组的大小。然后将过滤此分组的 DataFrame,并将数据绘制在条形图中。
我遇到的问题是,如果一个组的计数为零,则它不会显示在 DataFrame 中,因此不会出现在图上。因此,即使没有要显示的条形图,当我希望它们包含一个类别时,该图在 x 轴上也缺少类别(即将类别表示为零,从而使该图更能代表整个数据)。
# Import the required packages.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Set the appearance of plots.
plt.style.use('ggplot')
# Create sample DataFrame.
data = {'ID':[1, 2, 3, 4, 5, 6, 7], 'Name':['Tom', 'Jack', 'Anne', 'Steve', 'Ricky', 'Jane', 'Beth'], 'Age':[28,34,29,42,15,10,26], 'Voted':[0, 1, 0, 1, 1, 0, 0]}
df = pd.DataFrame(data)
# Bin into age groups and create an Age Group column in the DataFrame.
bins = list(range(0, 60, 10))
df['Age Group'] = pd.cut(df['Age'], bins, right=False)
# Group data by Age Group and Voted columns. Then perform count using the ID column. Make Age Group the new index.
groups = df.groupby(['Age Group', 'Voted'])
new_df = groups.agg({'ID': 'count'}).rename(columns={'ID':'Count'})
new_df.reset_index(inplace=True)
new_df.set_index('Age Group', inplace=True)
new_df
上面的代码会输出这个:
Voted ID
Age Group
[10, 20) 0 1
[10, 20) 1 1
[20, 30) 0 3
[30, 40) 1 1
[40, 50) 1 1
我想要的是类似下面的结果,从中我可以过滤掉投票=1 的年龄组并绘制在图表中:
Voted ID
Age Group
[0, 10) 0 0
[0, 10) 1 0
[10, 20) 0 1
[10, 20) 1 1
[20, 30) 0 3
[20, 30) 1 0
[30, 40) 0 0
[30, 40) 1 1
[40, 50) 0 0
[40, 50) 1 1
我已经搜索了类似的问题/结果(下面是最相关的),但我似乎都无法工作。
[Pandas groupby for zero values [Pandas Groupby How to Show Zero Counts in DataFrame
我还注意到,如果我只对单个列执行计数,零组确实会出现在 DataFrame 中。为什么是这样?例如:
# Group data by just Age Group column. Then perform count using the ID column.
groups = df.groupby(['Age Group'])
new_df = groups.agg({'ID': 'count'}).rename(columns={'ID':'Count'})
new_df # count displays the zero here for the 0-10 age group.
任何帮助解释这里发生的事情将不胜感激。
【问题讨论】:
标签: python pandas dataframe count pandas-groupby