Python Pandas中的聚合组,并从特定计数中吐出百分比

Kub*_*888 4 numpy aggregate-functions python-2.7 pandas

我试图通过在新列上创建百分比和求和来弄清楚如何在Pandas数据框中聚合组.

例如,在下面的数据框中,我有A,B,C和D列.我想按A中的组聚合,C应该是(1的频率除以非频率的百分比)缺失值),D应该是非缺失值的总和.

例如,对于'foo'组,结果数据框应为

A    B    C        D
foo       1.333    4
Run Code Online (Sandbox Code Playgroud)

我能够在这里和那里做一些单独的部分,但不知道如何在一个连贯的脚本中编译:

import pandas
from pandas import DataFrame
import numpy as np


df = DataFrame({'A' : ['foo', 'foo', 'foo', 'foo',
                        'bar', 'bar', 'bar', 'bar'],
                 'B' : ['one', 'one', 'two', 'three',
                        'two', 'two', 'one', 'three'],
                 'C' : [1, np.NaN, 1, 2, np.NaN, 1, 1, 2], 'D' : [2, '', 1, 1, '', 2, 2, 1]})

print df

#df.C.fillna(999, inplace=True)
df.D.replace('', np.NaN, inplace=True)

print df

grouped = df.groupby('A')

#print grouped.last()
#print grouped.sum()
#print grouped.mean()
#print grouped.count()

grouped_aggre = grouped.aggregate(np.sum)

print grouped_aggre
print df.D.mean()
print df.C.mean()

print '//////////////////'
print df.C.count()
print df.C.value_counts(dropna=True)
Run Code Online (Sandbox Code Playgroud)

此外,如何使用上述C和D列汇总统计数据按A和B列进行汇总?

原始数据框:

     A      B   C   D
0  foo    one   1   2
1  foo    one NaN NaN
2  foo    two   1   1
3  foo  three   2   1
4  bar    two NaN NaN
5  bar    two   1   2
6  bar    one   1   2
7  bar  three   2   1
Run Code Online (Sandbox Code Playgroud)

预期结果:

A    B    C        D
foo       1.333    4
bar       1.333    5
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 6

你可以groupby/agg用来执行求和和计数:

result = df.groupby(['A']).agg({'C': lambda x: x.sum()/x.count(), 'D':'sum'})
Run Code Online (Sandbox Code Playgroud)
import numpy as np
import pandas as pd

df = pd.DataFrame(
    {'A' : ['foo', 'foo', 'foo', 'foo',
            'bar', 'bar', 'bar', 'bar'],
     'B' : ['one', 'one', 'two', 'three',
            'two', 'two', 'one', 'three'],
     'C' : [1, np.NaN, 1, 2, np.NaN, 1, 1, 2], 
     'D' : [2, '', 1, 1, '', 2, 2, 1]})
df['D'].replace('', np.NaN, inplace=True)

result = df.groupby(['A']).agg({'C': lambda x: x.sum()/x.count(), 'D':'sum'})
print(result)
Run Code Online (Sandbox Code Playgroud)

产量

            C  D
A               
bar  1.333333  5
foo  1.333333  4
Run Code Online (Sandbox Code Playgroud)