0

Below are the columns in the DataFrame of data I am iterating on,

> incident_id                            int64 date                     
> object state                           object city_or_county          
> object address                         object n_killed                
> int64 n_injured                        int64 incident_url             
> object source_url                      object
> incident_url_fields_missing            bool congressional_district    
> float64 gun_stolen                     object gun_type               
> object incident_characteristics        object latitude                
> float64 location_description           object longitude              
> float64 n_guns_involved                float64 notes                  
> object participant_age                 object participant_age_group   
> object participant_gender              object participant_name        
> object participant_relationship        object participant_status      
> object participant_type                object sources                 
> object state_house_district            float64 state_senate_district  
> float64 dtype: object

and below is the code i have written,

def count_entries(df,col_name):
    """ Return a dictionary with counts of occurrences as value for each key"""
    cols_count = {}
    col = df[col_name]
    for entry in col:
        if entry in cols_count.keys():
            cols_count[entry] += 1
        else:
            cols_count = 1
    return cols_count
result = count_entries(data, 'gun_stolen')
print (result)
1
  • 4
    cols_count = 1? Commented Dec 2, 2018 at 9:44

2 Answers 2

3
def count_entries(df,col_name):
    """ Return a dictionary with counts of occurrences as value for each key"""
    cols_count = {}
    col = df[col_name]
    for entry in col:
        if entry in cols_count.keys():
            cols_count[entry] += 1
        else:
            # you forgot the [entry] in else statement.
            cols_count[entry] = 1
    return cols_count
result = count_entries(data, 'gun_stolen')
print (result)
Sign up to request clarification or add additional context in comments.

Comments

2

You can simplify solution with value_counts:

df = pd.DataFrame({
        'A':list('abcdef'),
         'F':list('aaabbc')
})

print (df)
   A  F
0  a  a
1  b  a
2  c  a
3  d  b
4  e  b
5  f  c

def count_entries(df,col_name):
    """ Return a dictionary with counts of occurrences as value for each key"""
    return df[col_name].value_counts().to_dict()

Or use collections.Counter:

from collections import Counter

def count_entries(df,col_name):
    """ Return a dictionary with counts of occurrences as value for each key"""
    return dict(Counter(df[col_name]))
result = count_entries(df, 'F')
print (result)
{'a': 3, 'b': 2, 'c': 1}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.