下面是我要迭代的数据的DataFrame列,
> 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
和下面是我编写的代码
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)
答案 0 :(得分:2)
您可以使用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()
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}
答案 1 :(得分:2)
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)