Python 属性错误:';int';对象没有属性';钥匙';
下面是我正在迭代的数据框架中的列 下面是我写的代码Python 属性错误:';int';对象没有属性';钥匙';,python,python-3.x,pandas,Python,Python 3.x,Pandas,下面是我正在迭代的数据框架中的列 下面是我写的代码 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():
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)
您可以通过以下方式简化解决方案: 或使用:
您可以通过以下方式简化解决方案: 或使用:
cols\u count=1
?cols\u count=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:
cols_count = 1
return cols_count
result = count_entries(data, 'gun_stolen')
print (result)
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}
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)