使用计数和百分比在 Python 中创建 Proc Frequency 表

Creating Proc Frequency tables in Python with count and percentage

我对 Python 比较陌生,但取得了一些稳固的进步,但是我在 SAS 中利用 Proc Freq 单向频率 tables 将我的过程转换为 python.

我的数据集的缩小版本如下:

import pandas as pd

data = {'Code':  [719, 719,719,719,719,719],
        'National': [1001, 1001,1001,1001,1001,1001],
        'Regional': [3005,3005,3005,3005,3005,3005],
         'Local': [2002,2002,2002,2002,2002,2002],
        'Collection Variable': [1,1,2,3,3,3]}


df = pd.DataFrame (data, columns = ['Code','National', 'Regional', 'Local','Collection Variable'])

SAS 中的输出将以此为集合变量列添加频率和百分比列,结果如下:

National  Regional  Local  Code  Collection  Count  Percent
                                  Variable   

  1001      3005    2002   719       1         2      0.333333
  1001      3005    2002   719       2         1      0.166667
  1001      3005    2002   719       3         3      0.5

在 python 中有这样的可能吗?我设法获得了百分比,但是 运行 在单独的列中,但无法获得额外的列。

此外,许多不同的集合变量都会发生这种情况。在 SAS 中,它为每个变量创建一个新的 table,在 python 中是否可以使用某种循环?

感谢您的帮助。

这两行应该足以获得 CountPercentage 列(它还占 nan 值):

df = df = df.astype(str).groupby(df.columns.tolist()).size().reset_index().rename(columns={0:'Count'})
df['Percentage'] = df[df['Collection Variable'] != 'nan']['Count'].apply(lambda x: x/sum(df[df['Collection Variable'] != 'nan']['Count']))

输出:

National  Regional  Local  Code  Collection  Count  Percent
                                  Variable   

  1001      3005    2002   719       1         2      0.333333
  1001      3005    2002   719       2         1      0.166667
  1001      3005    2002   719       3         3      0.5

希望对您有所帮助:)