1
import pandas as pd
import numpy as np 

df={'week':["Monday","Tuesday", "Monday", "Monday", "Tuesday"], 'Visits':[True, False, True, True, True]}

I would like to make a function wich counts all the "True" Visits and "False Visits" for all the days of the column "week" and transform it in a percentage. Here is the result expected:enter image description here

I have tried :

u = np.unique(df.week)
j = len(u)
for j in df.week = u[0]:
x=(df['Visits']==True).value_counts()
print(x)

But that does not work unfortunatelly. Thank you very much for you time and help.

1 Answers1

2

IIUC use:

df = pd.DataFrame({'week':["Monday","Tuesday", "Monday", "Monday", "Tuesday"], 
                   'Visits':[True, False, True, True, True]})

df = pd.crosstab(df['week'], df['Visits'], normalize=0).mul(100)
print(df)
Visits   False  True 
week                 
Monday     0.0  100.0
Tuesday   50.0   50.0
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • 1
    `df` of the original post is not a dataframe, need to add `df = pd.DataFrame({'week':["Monday","Tuesday", "Monday", "Monday", "Tuesday"], 'Visits':[True, False, True, True, True]})` – divingTobi Nov 08 '21 at 09:46