Anaconda / Jupyter Notebook Python 3 Distrlot Keyerror Исключение - PullRequest
0 голосов
/ 22 октября 2019

Я пытаюсь использовать цикл for для создания графиков распределения для некоторых переменных, которые я читаю из набора данных excel / csv. Код работает нормально до тех пор, пока не будут построены круговая диаграмма и гистограмма целевой переменной переменной пропорции. После круговой диаграммы и гистограммы я ожидал увидеть графики распределения, но выдается исключение KeyError.

    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    import warnings
    import itertools
    warnings.filterwarnings("ignore")
    #matplotlib inline

    print("This is a test right before excel file is read")

    # Utilize the pandas library to read the data
   dataset = pd.read_csv(r'C:\userpath\CSS581\Machine Learning             Project\pulsar_stars_test.csv')
   #dataset = pd.read_excel(r'C:\userpath\CSS581\Machine Learning Project\pulsar_stars_test.xlsx')


    # Print the number of rows and columns that the data has to the user
    print("This is the number of rows: ", dataset.shape[0])
    print("This is the number of columns: ", dataset.shape[1])

    # Use pandas to print out the information about the data
    print("This is the data information: ", dataset.info())

    # Use pandas to display information about missing data
    print("This is the missing data: ", dataset.isnull().sum())

    # Make a figure appear to display a dataset summary to the user
    plt.figure(figsize = (12, 8))
    sns.heatmap(dataset.describe()[1:].transpose(), annot = True,   linecolor = "w", linewidth = 2, cmap = sns.color_palette("Set2"))
    plt.title("Data Summary")
    plt.show()

    # Instantiate another figure to display some correlation data to the user
    correlation = dataset.corr()
    plt.figure(figsize = (10, 8))
    sns.heatmap(correlation, annot = True, cmap =     sns.color_palette("magma"), linewidth = 2, edgecolor = "k")
    plt.title("CORRELATION BETWEEN VARIABLES")
    plt.show()

    # Compute the proportion of each target variabibble in the dataset
    plt.figure(figsize = (12, 6))
    plt.subplot(121)
    ax = sns.countplot(y = dataset["target_class"], palette = ["r", "g"],     linewidth = 1, edgecolor = "k"*2)

    for i, j in enumerate(dataset["target_class"].value_counts().values):
ax.text(.7, i, j, weight = "bold", fontsize = 27)

    plt.title("Count for target variable in dataset")

    plt.subplot(122)
    plt.pie(dataset["target_class"].value_counts().values, labels = ["not    pulsar stars", "pulsar stars"], autopct = "%1.0f%%", wedgeprops =  {"linewidth":2, "edgecolor":"white"})
    #plt.pie(data["target_class"].value_counts().values, labels = ["not    pulsar stars", "pulsar stars"], autopct = "%1.0f%%", wedgeprops =   {"linewidth":2, "edgecolor":"white"})
    my_circ = plt.Circle((0,0), .7, color = "white")
    plt.gca().add_artist(my_circ)
    plt.subplots_adjust(wspace = .2)
    plt.title("Proportion of target variabibble in dataset")
    plt.show()

    for i, j, k in itertools.zip_longest(columns, range(length), colors): 

        plt.subplot(length/2,length/4,j+1)
        plt.subplot(length/2, length/4, j+1)
        sns.distplot(dataset[i], color = k)
        plt.title(i)
        plt.subplots_adjust(hspace = 0.3)
        plt.axvline(dataset[i].mean(), color = "k", linestyle = "dashed", label = "MEAN")
        plt.axvline(dataset[i].std(), color = "b", linestyle = "dotted", label = "STANDARD DEVIATION")
        plt.legend(loc = "upper right")

Я не очень знаком с anaconda / jupyter notebook / python, поэтому я не знаю, что исследоватьотносительно этой проблемы.

То, что я ожидал увидеть на выходе - это графики. Но я получил следующие сообщения об ошибках:

    KeyError                                  Traceback (most recent call last)
    ~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
       2656             try:
    -> 2657                 return self._engine.get_loc(key)
       2658             except KeyError:

    pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

    pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

    pandas/_libs/hashtable_class_helper.pxi in        pandas._libs.hashtable.PyObjectHashTable.get_item()

    pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

    KeyError: 'mean_dmnsr_curve'

    During handling of the above exception, another exception occurred:

    KeyError                                  Traceback (most recent call last)
    <ipython-input-8-c22a6f74190e> in <module>
         66     plt.subplot(length/2,length/4,j+1)
         67     plt.subplot(length/2, length/4, j+1)
    ---> 68     sns.distplot(dataset[i], color = k)
         69     plt.title(i)
         70     plt.subplots_adjust(hspace = 0.3)

    ~\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
       2925             if self.columns.nlevels > 1:
       2926                 return self._getitem_multilevel(key)
    -> 2927             indexer = self.columns.get_loc(key)
       2928             if is_integer(indexer):
       2929                 indexer = [indexer]

    ~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
       2657                 return self._engine.get_loc(key)
       2658             except KeyError:
    -> 2659                 return     self._engine.get_loc(self._maybe_cast_indexer(key))
       2660         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
       2661         if indexer.ndim > 1 or indexer.size > 1:

    pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

    pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

    pandas/_libs/hashtable_class_helper.pxi in         pandas._libs.hashtable.PyObjectHashTable.get_item()

    pandas/_libs/hashtable_class_helper.pxi in    pandas._libs.hashtable.PyObjectHashTable.get_item()

    KeyError: 'mean_dmnsr_curve'

Кто-нибудь знает, что может вызвать эти исключения? Я пытаюсь выяснить, есть ли у меня более одного исключения, потому что в сообщении об ошибке говорится «во время обработки вышеупомянутого исключения произошло другое исключение». Поскольку в сообщении об ошибке указано «еще одно исключение», означает ли это, что произошло два или более исключений? Кажется, что сообщение об ошибке ссылается на какое-то исключение, которое находится «выше». Но сообщение об ошибке не говорит, что это за исключение выше? Единственная строка в моем коде, которая указана как неисправная, это строка 68, где я вызываю sns.distplot.

...