aabujamra
aabujamra

Reputation: 4636

Counting the number of rows according to values in two different columns using Pandas

I have this dataframe, called "dem":

              code                                                CBO SEXO  \
47              58                                                NaN    F   
48              58                              Ajudante de motorista    F   
49              58                              Ajudante de motorista    M   
50              58                              Ajudante de motorista    M   
51              58                                           Brasador  NaN   
52              58                                           Brasador    M   
53              58                                           Brasador    M   

        FAIXA_IDADE                                ESCOLARIDADE
47  DE 21 A 30 ANOS                           Superior completo   
48  MAIS DE 50 ANOS                                         NaN   
49  DE 21 A 30 ANOS  Ginasial completo, ou Fundamental completo   
50  DE 41 A 50 ANOS    Colegial incompleto, ou Médio incompleto   
51  DE 41 A 50 ANOS        Colegial completo, ou Médio completo   
52  DE 41 A 50 ANOS        Colegial completo, ou Médio completo   
53  DE 41 A 50 ANOS  Ginasial completo, ou Fundamental completo

I want to know how many rows contain in the CBO column the words "motorista" or "Motorista" AND in the ESCOLARIDADE column contains the words "Fundamental completo". So, the result should be 1 (there are three rows where CBO contains "motorista" but in only one ESCOLARIDADE contains "Fundamental completo").

I tried:

try:
    mot_fund_comp=dem.loc[dem.CBO.str.contains('motorista|Motorista')].ESCOLARIDADE.str.contains['Fundamental completo'].count()
except:
    mot_fund_comp=0

I was always getting 0.

And:

When I apply this same line in the below dataframe, it brings me the result 1, when it should be ZERO...

dem:

               code                                                CBO SEXO  \
89               59                   Alimentador de linha de produção  NaN   
90               59                   Alimentador de linha de produção    M   
91               59                   Alimentador de linha de produção    M   
92               59                   Alimentador de linha de produção    M   
93               59               Assistente de laboratório industrial    F   
94               59                             Auxiliar de escritório    M   
95               59                     Auxiliar de manutenção predial    F   
96               59                                         Balanceiro    M   
97               59                                          Comprador    M   
98               59                          Desidratador de alimentos    M   
99               59                          Desidratador de alimentos    M   
100              59                          Desidratador de alimentos    M   
101              59                          Desidratador de alimentos    M   
102              59       Mecânico de manutenção de máquinas, em geral    M   
103              59  Motorista de caminhão (rotas regionais e inter...    M   
104              59  Operador de filtro-prensa (tratamentos químico...    M   
105              59                                           Soldador    M   
106              59                                           Soldador    M   
107              59                                           Soldador    M   

         FAIXA_IDADE                                 ESCOLARIDADE 
89   MAIS DE 50 ANOS         Colegial completo, ou Médio completo   
90   DE 21 A 30 ANOS                                          NaN   
91   DE 21 A 30 ANOS         Colegial completo, ou Médio completo   
92   DE 41 A 50 ANOS  Ginasial incompleto, ou entre 4ª e 8ª série   
93   DE 21 A 30 ANOS                                          NaN   
94   DE 21 A 30 ANOS         Colegial completo, ou Médio completo   
95   DE 41 A 50 ANOS         Colegial completo, ou Médio completo   
96   DE 21 A 30 ANOS         Colegial completo, ou Médio completo   
97   MAIS DE 50 ANOS         Colegial completo, ou Médio completo   
98   DE 21 A 30 ANOS         Colegial completo, ou Médio completo   
99   DE 31 A 40 ANOS         Colegial completo, ou Médio completo   
100  DE 31 A 40 ANOS   Ginasial completo, ou Fundamental completo   
101  MAIS DE 50 ANOS         Colegial completo, ou Médio completo   
102  DE 41 A 50 ANOS         Colegial completo, ou Médio completo   
103  DE 41 A 50 ANOS         Colegial completo, ou Médio completo   
104  DE 31 A 40 ANOS         Colegial completo, ou Médio completo   
105  DE 31 A 40 ANOS         Colegial completo, ou Médio completo   
106  DE 41 A 50 ANOS         Colegial completo, ou Médio completo   
107  MAIS DE 50 ANOS         Colegial completo, ou Médio completo

Would someone advise how to fix it or suggest another way to do it?

Upvotes: 2

Views: 99

Answers (2)

Stephen Strosko
Stephen Strosko

Reputation: 665

Here you go. I kept the column names the same but replaced motorista with yes, Motorista with yea, and Fundamental completo with yes_please.

     import pandas as pd
     import numpy as np

     data = {'CBO': ['yes', 'no', 'yea', 'no', 'yes'], 'escolaridade': 
             ['no', 'no', 'yes_please', 'yes_please', 'yes_please']}
     df = pd.DataFrame(data, columns=['CBO', 'escolaridade'])

     df['value'] = ((df['CBO'] == 'yes') | (df['CBO'] == 'yea')) & 
                   (df['escolaridade'] == 'yes_please')

That just created a new row that shows you which rows contain the values you want by using the flag True.

Then:

    df = df[df['value'] == True]

Gives you all the rows you want:

    CBO escolaridade    value
    2   yea yes_please  True
    4   yes yes_please  True

Showing rows 2 and 4 have the values you are looking for. From here you can easily gather the rows you need.

Upvotes: 2

aabujamra
aabujamra

Reputation: 4636

Thanks @roganjosh for giving inspiration to find the answer.

I noticed that when I use "|" as an OR operator inside a contains function, sometimes it work properly, sometimes it doesn't. If I use it like in here:

df=dem.CBO.str.contains('motorista|Motorista').sum()

It works fine. However, to solve my problem above, I had to adapt it, not using "|" inside the contains function. I changed the code to:

mot_fund_comp=dem.loc[dem.CBO.str.contains('motorista') | dem.CBO.str.contains('Motorista')].ESCOLARIDADE.str.contains['Fundamental completo'].sum()

Another detail: For some reason I couldn't track, if I used ".count()", values got wrong. If I used ".sum()" it worked perfectly.

Upvotes: 4

Related Questions