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

python pandas summarizing nominal variables (counting)

我有以下数据框:

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 列值的计数。

您可以通过创建一个值为 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()


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

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

您想获取 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