【问题标题】:Unable to pass a pandas Series to matplotlib fill_between无法将熊猫系列传递给 matplotlib fill_between
【发布时间】:2015-10-11 08:10:55
【问题描述】:

我正在使用 matplotlib fill_between 命令。

上下界 y1 和 y2 是“y 数据的 N 长度数组(或标量)

所以在我的代码中,我传递了 y1 和 y2 两个适当长度的熊猫系列。但是代码失败并出现错误:

TypeError: ufunc 'isfinite' 不支持输入类型,并且 输入无法安全地强制转换为任何支持的类型 强制转换规则“安全”

如果我改为传递简单的标量列表,则图表会正确呈现。

我认为数据系列将作为数组传递用于这些目的。但显然它没有。我发现onetwo StackOverflow 问题与相同的问题。在这两种情况下,答案都是传递 .values 属性。

不过,它对我不起作用。尽管为 yUpper、yLower 传递了 numpy.ndarrays,但我仍然得到与传递 pandas.Series 相同的错误。 !?

这是代码片段,下面是打印输出,以证明我正在通过我认为我正在通过的...

    high = OI_avg * 1.05
    low = OI_avg * 0.96
    print ("\nOI_avg {1} \n{0}".format(OI_avg, type(OI_avg)))
    print ("\nhigh {1} \n{0}".format(high, type(high)))
    print ("\nlow {1}\n{0}".format(low, type(low)))

    print ("high.values is type {0}".format(type(high.values)))
    print ("low.values is type {0}".format(type(low.values)))

    highHack = [-19914, 1951, 8650, 7031]
    lowHack = [-18207, 1784, 7909, 6428]

    # [CASE 1] passing a simple list of numbers works
    #fill_zone = plt.fill_between(index, highHack, lowHack, label = '+/-1 std dev range', facecolor='lightgray', alpha=0.3)

    # [CASE 2] passing two numpy.ndarray gives the ufunc error!?
    #fill_zone = plt.fill_between(index, high.values, low.values, label = '+/-1 std dev range', facecolor='lightgray', alpha=0.3)    

    # [CASE 3] passing two pandas.Series gives the ufunc error    
    #fill_zone = plt.fill_between(index, high, low, label = '+/-1 std dev range', facecolor='lightgray', alpha=0.3)

下面显示 .values 正在返回一个 np.ndarray。

OI_avg <class 'pandas.core.series.Series'> 
co1 comdty   -18966.1
co2 comdty     1858.7
co3 comdty     8238.9
co4 comdty     6696.5
Name: (d_OI, avg), dtype: object

high <class 'pandas.core.series.Series'> 
co1 comdty    -19914.4
co2 comdty    1951.635
co3 comdty    8650.845
co4 comdty    7031.325
Name: (d_OI, avg), dtype: object

low <class 'pandas.core.series.Series'>
co1 comdty   -18207.46
co2 comdty    1784.352
co3 comdty    7909.344
co4 comdty     6428.64
Name: (d_OI, avg), dtype: object
high.values is type <type 'numpy.ndarray'>
low.values is type <type 'numpy.ndarray'>

....所以当我写这个问题时,我意识到 high.values 给了我一个 'dtype = object' 的 ndarray。我想也许 matplotlib 对数据类型感到厌烦,所以我将数组的数据类型更改为浮点数。

highArray = high.values.astype(float)
lowArray = low.values.astype(float)

然后修复了它,现在代码可以工作了。让我想知道我是否将原始 pd.Series 的 dtype 更改为浮点数,那会起作用吗....答案是肯定的。我可以将 Series.astype(float) 直接传递给 matplotlib,它工作正常。无需通过 ndarray....

【问题讨论】:

  • 也许你应该将你的答案表述为一个答案......

标签: python numpy pandas matplotlib


【解决方案1】:

传递作为浮点数的系列值解决了问题

highArray = high.values.astype(float)

【讨论】:

    猜你喜欢
    • 2016-08-07
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 2022-01-23
    • 2022-08-10
    相关资源
    最近更新 更多