根据条件

时间:2017-12-13 13:22:29

标签: pandas

我有一个数据框:

   Id       age     gender      role       marital_status      sal

   231      42        F         0          single              42K
   134      77        M         1          married             89K
   222      34        M         0          married             56K
   453      22        F         1          single              44K
   546      32        F         1          married             45K

我需要根据性别和角色创建一份报告,其中marital_status已婚并且我需要为已婚客户的百分比添加另一个字段。

我怎样才能使用groupby语句。

提前致谢

所需的输出应该是: 性别角色marital_status:F 1结婚M 1结婚M 0结婚

1 个答案:

答案 0 :(得分:0)

你需要的IIUC:

df1 = df[df['marital_status'] == 'married'].copy()
df1['perc'] = len(df1.index) / len(df)
print (df1)
    Id  age gender  role marital_status  sal  perc
1  134   77      M     1        married  89K   0.6
2  222   34      M     0        Married  56K   0.6
4  546   32      F     1        Married  45K   0.6