3

我有以下数据框:

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

4

2 回答 2

4

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

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'])

图片

于 2016-09-27T18:20:50.787 回答
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
于 2016-09-27T18:21:30.643 回答