簡體   English   中英

Python'AttributeError:'function'對象沒有屬性'min''

[英]Python 'AttributeError: 'function' object has no attribute 'min''

首先,對這兩個問題的明顯程度表示歉意; 我對此非常陌生,不知道我在做什么。

我正在嘗試編寫一些東西來將 Scipy 函數用於樣條插值到值數組。 我的代碼目前看起來像這樣:

import numpy as np
import scipy as sp
from scipy.interpolate import interp1d

x=var
x1 = ([0.1,0.3,0.4])
y1 = [0.2,0.5,0.6]

new_length = 25
new_x = np.linspace(x.min(), x.max(), new_length)
new_y = sp.interpolate.interp1d(x, y, kind='cubic')(new_x)

但是當它到達線路時

new_x = np.linspace(x.min(), x.max(), new_length)

我收到以下錯誤:

AttributeError: 'function' object has no attribute 'min'

到目前為止,谷歌搜索等沒有發現我理解的任何內容。 這是什么意思,我該如何解決?

第二個問題:如何一次輸入多行代碼? 目前,如果我嘗試復制整個內容然后將其粘貼到 PyLab 中,它只會輸入我代碼的第一行,因此我必須一次將整個內容粘貼到一行中。 我該如何解決這個問題?

如果這條線

new_x = np.linspace(x.min(), x.max(), new_length)

正在生成錯誤消息

AttributeError: 'function' object has no attribute 'min'

那么x是一個函數,並且函數(通常)沒有min屬性,所以你不能調用some_function.min() x是什么? 在您的代碼中,您僅將其定義為

x=var

我不確定var是什么。 var不是 Python 中的默認內置函數,但如果它是一個函數,那么要么您出於某種原因自己定義它,要么從某個地方獲取它(假設您正在使用 Sage,或者您做了星型導入)像from sympy import * 。)

[更新:既然你說你在“使用 PyLab”,可能varnumpy.var ,它在 IPython 啟動時被導入到作用域中。 我認為你的意思是“在--pylab模式下使用 IPython。]

您還定義了x1y1 ,但是后來的代碼引用了xy ,所以感覺這段代碼介於兩個功能狀態之間。

現在numpy數組確實有一個.min().max()方法,所以這個:

>>> x = np.array([0.1, 0.3, 0.4, 0.7])
>>> y = np.array([0.2, 0.5, 0.6, 0.9])
>>> new_length = 25
>>> new_x = np.linspace(x.min(), x.max(), new_length)
>>> new_y = sp.interpolate.interp1d(x, y, kind='cubic')(new_x)

會工作。 你的測試數據不會,因為插值需要至少 4 個點,你會得到

ValueError: x and y arrays must have at least 4 entries

第二個問題:如何一次輸入多行代碼? 目前,如果我嘗試復制整個內容然后將其粘貼到 PyLab 中,它只會輸入我代碼的第一行,因此我必須一次將整個內容粘貼到一行中。 我該如何解決這個問題?

假設你在ipython被稱為ipython --pylab或類似的東西,那么你可以簡單地使用paste magic command 如果您尚未將paste定義為另一個變量,則將其稱為%paste或簡單地paste

In [8]: paste
import numpy as np
import scipy as sp
from scipy.interpolate import interp1d

x=var
x1 = ([0.1,0.3,0.4])
y1 = [0.2,0.5,0.6]

new_length = 25
new_x = np.linspace(x.min(), x.max(), new_length)
new_y = sp.interpolate.interp1d(x, y, kind='cubic')(new_x)

## -- End pasted text --
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-b4e41f59d719> in <module>()
      3 from scipy.interpolate import interp1d
      4 
----> 5 x=var
      6 x1 = ([0.1,0.3,0.4])
      7 y1 = [0.2,0.5,0.6]

NameError: name 'var' is not defined

In [9]: 

將該行更改為:

new_x = np.linspace(min(x), max(x), new_length)

minmax不是列表的屬性,它們是它們自己的函數。

當我調用timezone.now而不是timezone.now() timezone.now ,我遇到了類似的錯誤。 然后我嘗試格式化我期望的DateTime值。 但它不是DateTime 這是一個函數。 這導致了關於“Month”不是“function”的屬性的錯誤消息。

解決方法是在now之后簡單地添加括號。 這會調用now函數並返回其結果,而不是返回now function對象本身。

愚蠢的錯誤,我知道。 但不容易排除故障。

我得到了類似的問題。

我的錯誤是我將變量和函數名稱命名為相同。

我糾正了這一點,錯誤消失了。

Int 沒有 min() 函數,但 min() 是一個內置函數。 您需要使用 min(x)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM