我可以呼叫通過 Pandas 系列上的字串變數定義的任意方法。我會這樣做的方式是這樣的:
import pandas as pd
method_name = 'mean'
pd.Series([1, 2, 3]).__getattr__(method_name)()
現在我想對滾動的熊貓系列做同樣的事情,我會這樣做:
import pandas as pd
method_name = 'mean'
pd.Series([1, 2, 3]).rolling(window=1).__getattr__(method_name)()
執行此操作時出現以下錯誤:
AttributeError: 'Rolling' object has no attribute 'mean'
有沒有辦法在滾動的熊貓系列上呼叫任意方法(平均值、中值、最大值、最小值、分位數)?
謝謝!
uj5u.com熱心網友回復:
您可以從 Python 檔案(資料模型)中了解getattr和getattribute:getattr和getattribute
使用getattribute將解決您的問題;
import pandas as pd
method_name = 'mean'
pd.Series([1, 2, 3]).rolling(window=1).__getattribute__(method_name)()
輸出
0 1.0
1 2.0
2 3.0
dtype: float64
uj5u.com熱心網友回復:
__getattr__必須為每個物件實作該方法。這與Python__getatrribute__基object類中的方法不同。呼叫時__getatrr__,您將獲得此方法的物件實作(如果有)。對于rolling,定義如下,它基本上對快取/酸洗目的(the _internal_names_set)進行了一些檢查,如果沒有找到,它會檢查資料幀(the self.obj):
def __getattr__(self, attr: str):
if attr in self._internal_names_set:
return object.__getattribute__(self, attr)
if attr in self.obj:
return self[attr]
raise AttributeError(
f"'{type(self).__name__}' object has no attribute '{attr}'"
)
為避免這種情況,請使用getattr內置函式:
>> getattr(df.rolling(3), 'mean')
我喜歡,getattr因為它允許您在未定義屬性時指定第三個可選引數:
>> getattr(df.rolling(3), 'mean', None)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/362549.html
