首页 > 解决方案 > KeyError - 不明白为什么

问题描述

尝试获取所有付款方式实例的计数:

    def paymentMethod(self):
        # Stores unique payment methods as dictionary keys with count of times used as values
        myDict = {}
        keyList = list(self.df['Institution'].unique())

        for i in keyList:
            count = self.df.groupby(i).count()
            myDict.update(i, count)

        print(myDict)

这是我的错误:

Traceback (most recent call last):
  File "final.py", line 40, in <module>
    x.paymentMethod()
  File "final.py", line 29, in paymentMethod
    count = self.df.groupby(i).count()
  File "C:\Users\Sean\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\frame.py", line 6515, in groupby
    return DataFrameGroupBy(
  File "C:\Users\Sean\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\groupby\groupby.py", line 525, in __init__
    grouper, exclusions, obj = get_grouper(
  File "C:\Users\Sean\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\groupby\grouper.py", line 786, in get_grouper
    raise KeyError(gpr)
KeyError: 'Chase Checking'

我真的不明白错误试图告诉我什么?对不起,如果这是一个nooby问题。

标签: pythonpandasdictionary

解决方案


groupby列名上的组。您的数据框没有名为'Chase Checking'.

你似乎在寻找这个:

def paymentMethod(self):
    # Stores unique payment methods as dictionary keys with count of times used as values
    myDict = self.df['Institution'].value_counts().to_dict()

    print(myDict)

推荐阅读