【问题标题】:python pandas summarizing nominal variables (counting)python pandas总结名义变量(计数)
【发布时间】:2017-02-05 11:35:27
【问题描述】:

我有以下数据框:

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

【问题讨论】:

  • 嗨,Felix,到目前为止,您尝试了什么?
  • 试过 pd.melt 和 pd.pivot_table。没有成功
  • 嘿,Felix,你能给我们一个代码行中的 df 样本,以便我们使用它吗?
  • @StevenG, read_clipboard() 是你的朋友 ;)

标签: python pandas dataframe summarize


【解决方案1】:

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

【讨论】:

  • 啊,我忘了crosstab!不错的解决方案!
  • 即使是我。只是想起了它。之前是按照groupby/pivot的思路思考的。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    相关资源
    最近更新 更多