How to calculate percentage probability using a pivot table in pandas

Viewed 30

I am working with a dataframe with two columns. One column is coded for either "control" or "treatment" while the other column is "true" or "false". I was wondering how I could use a pivot table and/or groupby to calculate the probability of true or false given either the control or treatment group.

1 Answers

You can groupby and use value_counts with normalize=True

df = pd.DataFrame({
    'Group':['C','C','C','T','T','T','T'],
    'Result':[True,True,False,False,False,False,True],
})

p_df = (
    df.groupby('Group')['Result']
    .value_counts(normalize=True)
    .reset_index(name='p')
)

print(p_df)

Output

enter image description here

Related