将函数应用于pandas groupby

时间:2013-03-13 00:01:14

标签: python pandas

我有一个pandas数据框,其中包含一个名为my_labels的列,其中包含字符串:'A', 'B', 'C', 'D', 'E'。我想计算每个字符串的出现次数,然后将计数的数量除以所有计数的总和。我想在Pandas这样做:

func = lambda x: x.size() / x.sum()
data = frame.groupby('my_labels').apply(func)

此代码抛出错误,'DataFrame对象没有属性'size'。如何在Pandas中应用函数来计算它?

5 个答案:

答案 0 :(得分:34)

apply需要一个函数来应用每个值,而不是系列,并接受kwargs。 因此,这些值没有.size()方法。

也许这会奏效:

from pandas import *

d = {"my_label": Series(['A','B','A','C','D','D','E'])}
df = DataFrame(d)


def as_perc(value, total):
    return value/float(total)

def get_count(values):
    return len(values)

grouped_count = df.groupby("my_label").my_label.agg(get_count)
data = grouped_count.apply(as_perc, total=df.my_label.count())

此处.agg()方法采用的函数应用于groupby object所有值。

答案 1 :(得分:8)

尝试:

g = pd.DataFrame(['A','B','A','C','D','D','E'])

# Group by the contents of column 0 
gg = g.groupby(0)  

# Create a DataFrame with the counts of each letter
histo = gg.apply(lambda x: x.count())

# Add a new column that is the count / total number of elements    
histo[1] = histo.astype(np.float)/len(g) 

print histo

输出:

   0         1
0             
A  2  0.285714
B  1  0.142857
C  1  0.142857
D  2  0.285714
E  1  0.142857

答案 2 :(得分:2)

As of Pandas version 0.22,还有applypipe的替代方法,可以比使用apply快得多(您还可以检查this question这两种功能之间存在更多差异)。

对于你的例子:

df = pd.DataFrame({"my_label": ['A','B','A','C','D','D','E']})

  my_label
0        A
1        B
2        A
3        C
4        D
5        D
6        E

apply

df.groupby('my_label').apply(lambda grp: grp.count() / df.shape[0])

给出

          my_label
my_label          
A         0.285714
B         0.142857
C         0.142857
D         0.285714
E         0.142857

pipe版本

df.groupby('my_label').pipe(lambda grp: grp.size() / grp.size().sum())

产量

my_label
A    0.285714
B    0.142857
C    0.142857
D    0.285714
E    0.142857

所以值是相同的,但是,时间差异很大(至少对于这个小数据帧):

%timeit df.groupby('my_label').apply(lambda grp: grp.count() / df.shape[0])
100 loops, best of 3: 5.52 ms per loop

%timeit df.groupby('my_label').pipe(lambda grp: grp.size() / grp.size().sum())
1000 loops, best of 3: 843 µs per loop

将它包装成函数也很简单:

def get_perc(grp_obj):
    gr_size = grp_obj.size()
    return gr_size / gr_size.sum()

现在你可以打电话了

df.groupby('my_label').pipe(get_perc)

产生

my_label
A    0.285714
B    0.142857
C    0.142857
D    0.285714
E    0.142857

但是,对于这种特殊情况,您甚至不需要groupby,但您可以像这样使用value_counts

df['my_label'].value_counts(sort=False) / df.shape[0]

产生

A    0.285714
C    0.142857
B    0.142857
E    0.142857
D    0.285714
Name: my_label, dtype: float64

对于这个小型数据帧,它非常快

%timeit df['my_label'].value_counts(sort=False) / df.shape[0]
1000 loops, best of 3: 770 µs per loop

正如@anmol所指出的,最后一句话也可以简化为

df['my_label'].value_counts(sort=False, normalize=True)

答案 3 :(得分:1)

我看到了一种用于计算S.O.加权平均值的嵌套函数技术。有一次,改变这种技术可以解决你的问题。

def group_weight(overall_size):
    def inner(group):
        return len(group)/float(overall_size)
    inner.__name__ = 'weight'
    return inner

d = {"my_label": pd.Series(['A','B','A','C','D','D','E'])}
df = pd.DataFrame(d)
print df.groupby('my_label').apply(group_weight(len(df)))



my_label
A    0.285714
B    0.142857
C    0.142857
D    0.285714
E    0.142857
dtype: float64

以下是如何在群组中进行加权平均

def wavg(val_col_name,wt_col_name):
    def inner(group):
        return (group[val_col_name] * group[wt_col_name]).sum() / group[wt_col_name].sum()
    inner.__name__ = 'wgt_avg'
    return inner



d = {"P": pd.Series(['A','B','A','C','D','D','E'])
     ,"Q": pd.Series([1,2,3,4,5,6,7])
    ,"R": pd.Series([0.1,0.2,0.3,0.4,0.5,0.6,0.7])
     }

df = pd.DataFrame(d)
print df.groupby('P').apply(wavg('Q','R'))

P
A    2.500000
B    2.000000
C    4.000000
D    5.545455
E    7.000000
dtype: float64

答案 4 :(得分:0)

关于“大小”的问题,大小不是数据帧上的函数,而是属性。因此,应该使用普通大小而不是使用size()

除此之外,这样的方法应该有效

 def doCalculation(df):
    groupCount = df.size
    groupSum = df['my_labels'].notnull().sum()

    return groupCount / groupSum

dataFrame.groupby('my_labels').apply(doCalculation)
相关问题