首页 > 解决方案 > 在 pandas 数据框中的列列表中应用转换的属性错误

问题描述

嗨,我有一个数据框和一个列列表,我想对其执行循环:

#list of the 4 columns i want to perform function on
columnnames= ['a','b','c','d']


#Function
for col in columnnames:
    df[f"{col}_new"] = df.groupby('Name')[col].transform(lambda x: x.rolling(20).apply(ewma).shift())

当我运行此循环时,我收到以下错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-21-519963825599> in <module>
      8 ewma = partial(np.average, weights=weights)
      9 for col in columnnames:
---> 10     df[f"{col}_new"] = df.groupby('Name')[col].transform(lambda x: x.rolling(20).apply(ewma).shift())
     11 
     12 #df['testcolumn'] = df['test']*2

~\anaconda3\lib\site-packages\pandas\core\groupby\generic.py in transform(self, func, *args, **kwargs)
    463 
    464         if not isinstance(func, str):
--> 465             return self._transform_general(func, *args, **kwargs)
    466 
    467         elif func not in base.transform_kernel_whitelist:

~\anaconda3\lib\site-packages\pandas\core\groupby\generic.py in _transform_general(self, func, *args, **kwargs)
    507         # we have a numeric dtype, as these are *always* user-defined funcs
    508         # the cython take a different path (and casting)
--> 509         dtype = self._selected_obj.dtype
    510         if is_numeric_dtype(dtype):
    511             result = maybe_downcast_to_dtype(result, dtype)

~\anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
   5272             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5273                 return self[name]
-> 5274             return object.__getattribute__(self, name)
   5275 
   5276     def __setattr__(self, name: str, value) -> None:

AttributeError: 'DataFrame' object has no attribute 'dtype'

关于我的问题可能是什么的任何想法?

我已经在不同的数据帧(非常相似)上成功运行了它,所以我只是不知道这个错误告诉我什么。

非常感谢!

标签: pythonpandas

解决方案


原来我的错误是我有一些同名的列!


推荐阅读