Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas count occurence of value in dictionary

Tags:

python

pandas

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

like image 595
jxn Avatar asked Jan 01 '23 01:01

jxn


2 Answers

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
like image 113
Quang Hoang Avatar answered Jan 14 '23 06:01

Quang Hoang


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
like image 30
anky Avatar answered Jan 14 '23 04:01

anky