【问题标题】:Pandas Plot with Index causes 'KeyError [] not in index'带有索引的 Pandas Plot 导致“KeyError [] 不在索引中”
【发布时间】:2017-03-02 11:46:08
【问题描述】:

我对 Python 中的 Pandas 概念非常陌生。通常地块不是问题。但是,我现在面临一个包含索引的数据框。不知何故,什么都没有了。

我想要达到的目标: 为每一列 [Plant1,Plant2,Plant3] 针对一个特定列 [Trafo1] 创建一个子图。

这是我的代码:

import numpy as np
import datetime
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import os

# Create the sample data

plant1 = {'Date' : pd.date_range('1/1/2011', periods=10, freq='D'),
     'Plant' : pd.Series(["Plant1"]*10),
     'Output' : pd.Series(abs(np.random.randn(10)))}

plant2 = {'Date' : pd.date_range('1/3/2011', periods=10, freq='D'),
     'Plant' : pd.Series(["Plant2"]*10),
     'Output' : pd.Series(abs(np.random.randn(10)))}

plant3 = {'Date' : pd.date_range('1/5/2011', periods=10, freq='D'),
     'Plant' : pd.Series(["Plant3"]*10),
     'Output' : pd.Series(abs(np.random.randn(10)))}     

trafo1 = {'Date' : pd.date_range('1/5/2011', periods=10, freq='D'),
     'Plant' : pd.Series(["Trafo1"]*10),
     'Output' : pd.Series(abs(np.random.randn(10)))}          

trafo2 = {'Date' : pd.date_range('1/5/2011', periods=10, freq='D'),
     'Plant' : pd.Series(["Trafo2"]*10),
     'Output' : pd.Series(abs(np.random.randn(10)))}          



df_plant_1 = pd.DataFrame(plant1)
df_plant_2 = pd.DataFrame(plant2)
df_plant_3 = pd.DataFrame(plant3)
df_trafo_1 = pd.DataFrame(trafo1)
df_trafo_2 = pd.DataFrame(trafo2)


sample = pd.concat([df_plant_1,df_plant_2,df_plant_3,df_trafo_1,df_trafo_2])
test = pd.pivot_table(sample, index='Date', columns='Plant', values='Output')
test = test.fillna(method='pad')                            
test = test.fillna(method='bfill')     



# Draw the plots

matplotlib.style.use('ggplot')

cols = len(test.columns) - 1

fig, axes = plt.subplots(nrows=cols/2, ncols=2, figsize=(12, 4))
for column in test.iloc[:,:-1]:
    test.plot(x=test[column], y=test['Trafo1'], title=column)
    plt.gca().set_aspect('equal', adjustable='box')
    plt.show()

导致以下错误输出:

runfile('C:/..../untitled12.py', wdir='C:/...')


Traceback (most recent call last):

  File "<ipython-input-206-1acb55933d7f>", line 1, in <module>
    runfile('C:/Users/bjl/untitled12.py', wdir='C:/Users/bjl')

  File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
    execfile(filename, namespace)

  File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "C:/Users/bjl/untitled12.py", line 52, in <module>
    test.plot(x=test[column], y=test['Trafo1'], title=column)

  File "C:\Anaconda2\lib\site-packages\pandas\tools\plotting.py", line 3671, in __call__
    sort_columns=sort_columns, **kwds)

  File "C:\Anaconda2\lib\site-packages\pandas\tools\plotting.py", line 2556, in plot_frame
    **kwds)

  File "C:\Anaconda2\lib\site-packages\pandas\tools\plotting.py", line 2370, in _plot
    series = data[y].copy()  # Don't modify

  File "C:\Anaconda2\lib\site-packages\pandas\core\frame.py", line 1963, in __getitem__
    return self._getitem_array(key)

  File "C:\Anaconda2\lib\site-packages\pandas\core\frame.py", line 2007, in _getitem_array
    indexer = self.ix._convert_to_indexer(key, axis=1)

  File "C:\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1150, in _convert_to_indexer
    raise KeyError('%s not in index' % objarr[mask])

KeyError: '[ 1.20311253  1.20311253  1.20311253  1.20311253  1.20311253  0.32765014\n  1.65686117  2.58118029  0.58903059  0.13907876  0.59270297  0.27072611\n  0.50167366  1.0310578 ] not in index'

我不明白索引的问题是什么。我无法在网上找到任何帮助,因为所有示例都没有索引。

非常感谢您的帮助。这个错误对新手来说是个谜。

【问题讨论】:

    标签: python pandas plot


    【解决方案1】:

    根据docs,您应该在以这种方式绘制时给出列名,而不是列本身。所以替换:

    test.plot(x=test[column], y=test['Trafo1'], title=column)
    

    test.plot(x=column, y='Trafo1', title=column)
    

    应该解决这个错误。

    编辑: 至于子图,要将其放在正确的子图中,您必须指定您希望图结束的轴。您可以通过以下方式这样做:

    for i, column in enumerate(test.iloc[:, :-2]):
        j = i // 2
        k = i % 2
        test.plot(x=column, y='Trafo1', title=column, ax=axes[j][k])
    

    现在在所有轴上执行您想要的操作(虽然它确实搞砸了)

    for ax in axes.reshape(4):
        ax.set_aspect('equal', adjustable='box')
    

    显示图:)

    plt.show()
    

    【讨论】:

    • 我应该订个假期:(
    • @lammy 恰好发生在我们当中;)。我在下一次编辑中也修复了子图,但我还没有弄清楚如何在右轴上进行 set_aspect 操作。不过从现在开始应该不会那么难了!
    • 如果你能做到这一点,我也会预订你的位置 :) 我目前正在尝试创建子图,并按照所述对数据框进行迭代。还没有成功。那些日子之一...... ;)
    • 全部完成 :) set_aspect 的东西真的很丑,所以我假设这不是你想要的。我们要去哪里度假?
    猜你喜欢
    • 2016-11-22
    • 2018-04-30
    • 1970-01-01
    • 2018-05-16
    • 2020-02-03
    • 2017-01-07
    • 2015-07-27
    • 1970-01-01
    • 2018-03-19
    相关资源
    最近更新 更多