分组,计算和计算熊猫的中位数

时间:2018-03-01 14:51:38

标签: python pandas pandas-groupby

我有这个数据框:

df:
      type . size .  margin .  height
0 .      A .    2 .       5 .       1
1 .      A .    3 .       4 .       1
2 .      B .    1 .       1 .       3 

我想分组类型,计算每种类型的公司数量并计算所有列的中位数。

我知道计数就像这样

df=df.groupby('type').count('type')

但是有没有办法使用一个衬垫并将所有东西放在同一个df中?

类似的东西:

df=df.groupby('type').calculate_medians_and_counts

应该看起来像这样:

type    count   size   margin   height
   A        2    2.5      4.5        1
   B        1      1        1        3

(size, margin and height are the medians from df)

2 个答案:

答案 0 :(得分:1)

按字典使用agg

d = {'size':'median', 'margin':'median', 'height':'median', 'type':'size'}

如果可以使用多列,请动态创建dict

d = dict.fromkeys(df.columns.difference(['type']), 'median')
d['type'] = 'size'
df = df.groupby('type').agg(d).rename(columns={'type':'count'}).reset_index()

join的另一种选择:

df = df.groupby('type').median().join(df.type.value_counts().rename('count')).reset_index()
print (df)
  type  margin  size  height  count
0    A     4.5   2.5       1      2
1    B     1.0   1.0       3      1

答案 1 :(得分:1)

我将使用median基于索引级别= 0 + value_counts

pd.concat([df.set_index('type').median(level=0),df.type.value_counts()],1)
Out[787]: 
      size  margin  height  type
type                            
A      2.5     4.5     1.0     2
B      1.0     1.0     3.0     1
相关问题