首页 > 解决方案 > 向 Pandas.Series 添加自定义属性

问题描述

我正在尝试为 pd.DataFrame 内的每个 pd.Series 添加一个自定义属性。具体来说,我得到了一个 CSV,其中,颜色代码间歇性地嵌入在列标题中。我想在绘图之前将它们预处理成一个属性 - 并将默认颜色分配给其他未指定的列。

但就其核心而言,我只需要在某个地方的系列中添加一个自定义属性,就像您可能在任何其他 Python 对象上一样。简化示例:

>>> import pandas as pd
>>> df = pd.DataFrame({"Low":[1,2,3], "Medium":[4,5,6], "High":[7,8,9]})
>>> s1 = df.iloc[:,1]
>>> 
>>> s1.color = 'yellow'
>>> print(s1.color)
yellow
>>>
>>> type(s1)
<class 'pandas.core.series.Series'>
>>>
>>> ### assign back to the DataFrame...
>>> df.iloc[:,1] = s1
>>>
>>> print(df.iloc[:,1].color)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/generic.py", line 5487, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'Series' object has no attribute 'color' 
>>>
>>>
>>> ### Drat... maybe assigning directly to the Series object:
>>> setattr(df.iloc[:,1], 'color', 'yellow')
>>> 
>>> ### goes in ok, but...
>>> df.iloc[:,1].color
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/generic.py", line 5487, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'Series' object has no attribute 'color'
>>> 

显然 pandas 不仅仅是传递指针。我不需要序列化,但我确实需要该属性才能在运行时函数之间传递。

我宁愿不为一个属性子类化整个数据框/系列模型。厌倦了我的头脑,我的目标是为数据框创建一个包装类,该类存储颜色和系列索引之间的属性映射,但是......再一次,对于 python 对象上的 +1 属性似乎很混乱.

对最简单/最干净的解决方案有任何想法吗?

标签: pythonpython-3.xpandasdataframeseries

解决方案


我认为我在类似问题中的回答可以帮助您我认为您需要一个自定义属性访问器来扩展 Pandas 系列


推荐阅读