Given a DF:
pd.DataFrame({"A":[1,2,3],
"B": [{"Mon":"Closed", "Tue":"Open", "Wed":"Closed"},
{"Mon":"Open", "Tue":"Open", "Wed":"Closed"},
{"Mon":"Open", "Tue":"Open", "Wed":"Open"}]
})
How do i get a count of number of times "Closed" appears in the dict?
A B count
1 {..} 2
2 {..} 1
3 {..} 0
I really don't know how to start on this to try
You can do an apply
:
df['count'] = df.B.apply(pd.Series).eq('Closed').sum(1)
Output:
A B count
0 1 {'Mon': 'Closed', 'Tue': 'Open', 'Wed': 'Closed'} 2
1 2 {'Mon': 'Open', 'Tue': 'Open', 'Wed': 'Closed'} 1
2 3 {'Mon': 'Open', 'Tue': 'Open', 'Wed': 'Open'} 0
You can try converting the series of dictionary into a dataframe and then stack
, then take sum of Closed
values on level=0 to get Count per row:
df['Count_closed'] = pd.DataFrame(df['B'].tolist()).stack().eq("Closed").sum(level=0)
A B Count_closed
0 1 {'Mon': 'Closed', 'Tue': 'Open', 'Wed': 'Closed'} 2.0
1 2 {'Mon': 'Open', 'Tue': 'Open', 'Wed': 'Closed'} 1.0
2 3 {'Mon': 'Open', 'Tue': 'Open', 'Wed': 'Open'} 0.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With