有没有一种方法可以使用groupby来计算和计算文本列的均值?

时间:2020-05-31 04:06:26

标签: python pandas pandas-groupby

我一直在使用pandas.groupby来透视数据并为我的数据创建描述性图表和表格。在对三个变量进行分组比较时,在使用DataError: No numeric types to aggregate列时,我一直遇到cancelled错误。

为了描述我的数据,YearMonth包含多列(多年,所有月份)的年度和月度数据,Type包含订单项的类型(衣服,设备,等等),而cancelled包含是或否字符串值以确定订单是否被取消。

我希望绘制一个图表并显示一个表格,以显示按订单项显示的取消率(和成功率)。以下是到目前为止我正在使用的

df.groupby(['Year', 'Month', 'Type'])['cancelled'].mean()

但这似乎不起作用。

样品

Year    Month        Type          cancelled 
2012      1        electronics       yes
2012      10         fiber           yes
2012      9         clothes          no
2013      4        vegetables        yes
2013      5        appliances        no
2016      3        fiber             no
2017      1        clothes           yes

2 个答案:

答案 0 :(得分:2)

使用:

df = pd.DataFrame({
         'Year':[2020] * 6,
         'Month':[7,8,7,8,7,8],
         'cancelled':['yes','no'] * 3,
         'Type':list('aaaaba')
})
print (df)

获取每YearMonthType列的计数:

df1 = df.groupby(['Year', 'Month', 'Type','cancelled']).size().unstack(fill_value=0)
print (df1)
cancelled        no  yes
Year Month Type         
2020 7     a      0    2
           b      0    1
     8     a      3    0

然后除以比率值之和:

df2 = df1.div(df1.sum()).mul(100)
print (df2)
cancelled           no        yes
Year Month Type                  
2020 7     a       0.0  66.666667
           b       0.0  33.333333
     8     a     100.0   0.000000

答案 1 :(得分:1)

可能是我误解了您希望输出的样子,但是要找到每种商品类型的取消率,您可以执行以下操作:

# change 'cancelled' to numeric values
df.loc[df['cancelled'] == 'yes', 'cancelled'] = 1
df.loc[df['cancelled'] == 'no', 'cancelled'] = 0

# get the mean of 'cancelled' for each item type
res = {}
for t in df['Type'].unique():
    res[t] = df.loc[df['Type'] == t, 'cancelled'].mean()

# if desired, put it into a dataframe
results = pd.DataFrame([res], index=['Rate']).T

输出:

              Rate
electronics   1.0
fiber         0.5
clothes       0.5
vegetables    1.0
appliances    0.0

注意:如果要指定特定的年份或月份,也可以使用loc进行设置,但是鉴于示例数据在给定的年份或月份内没有任何重复,这将返回您的给定示例的原始数据框。