python pandas总结名义变量(计数)

时间:2016-09-27 17:59:58

标签: python pandas dataframe summarize

我有以下数据框:

KEY PROD PARAMETER Y/N
1    AAA    PARAM1   Y
1    AAA    PARAM2   N
1    AAA    PARAM3   N
2    AAA    PARAM1   N
2    AAA    PARAM2   Y
2    AAA    PARAM3   Y
3    CCC    PARAM1   Y
3    CCC    PARAM2   Y
3    CCC    PARAM3   Y

我有兴趣通过PROD和PARAMETER列汇总Y / N列值并获得以下输出:

PROD  PARAM Y N
 AAA PARAM1 1 1
 AAA PARAM2 1 1
 AAA PARAM3 1 1
 CCC PARAM1 1 0
 CCC PARAM2 1 0
 CCC PARAM3 1 0

虽然Y和N值是来自原始数据帧的Y / N列值的计数。

2 个答案:

答案 0 :(得分:4)

你可以通过创建一个值为1的附加列来使用pivot_table,因为这两种方式无关紧要(你只计算它们)

df['Y/Ncount'] = 1

df = df.pivot_table(index=['PROD', 'PARAMETER'], columns=['Y/N'], values=['Y/Ncount'], 
                    aggfunc=sum, fill_value=0)

df.columns = [col for col in df.columns.get_level_values(1)]
df.reset_index()

Image

在这种情况下使用的最简单操作是crosstab,它将产生Y / N列中存在的值的频率计数:

pd.crosstab([df['PROD'], df['PARAMETER']], df['Y/N'])

Image

答案 1 :(得分:3)

您希望获取Y/N列中值的计数,按PRODPARAMETER分组。

import io
import pandas as pd

data = io.StringIO('''\
KEY PROD PARAMETER Y/N
1    AAA    PARAM1   Y
1    AAA    PARAM2   N
1    AAA    PARAM3   N
2    AAA    PARAM1   N
2    AAA    PARAM2   Y
2    AAA    PARAM3   Y
3    CCC    PARAM1   Y
3    CCC    PARAM2   Y
3    CCC    PARAM3   Y
''')
df = pd.read_csv(data, delim_whitespace=True)

res = (df.groupby(['PROD', 'PARAMETER'])['Y/N'] # Group by `PROD` and `PARAMETER`
                                                # and select the `Y/N` column
         .value_counts()                        # Get the count of values
         .unstack('Y/N')                        # Long-to-wide format change
         .fillna(0)                             # Fill `NaN`s with zero
         .astype(int))                          # Cast to integer
print(res)

输出:

Y/N             N  Y
PROD PARAMETER      
AAA  PARAM1     1  1
     PARAM2     1  1
     PARAM3     1  1
CCC  PARAM1     0  1
     PARAM2     0  1
     PARAM3     0  1