Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 属性错误:';int';对象没有属性';钥匙';_Python_Python 3.x_Pandas - Fatal编程技术网

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)