[英]AttributeError: 'int' object has no attribute 'keys'
Below are the columns in the DataFrame of data I am iterating on, 以下是我要迭代的数据的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
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)
You can simplify solution with value_counts
: 您可以使用
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
: 或使用
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}
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.