python - 向 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 属性似乎很混乱.
对最简单/最干净的解决方案有任何想法吗?
解决方案
推荐阅读
- parse-server - 关于 config.json 配置的文档?
- c# - Arch linux(.net)中的开发证书
- java - 如何使用 Java 将字符串添加到 mongodb 中现有的数组
- bash - 如何删除站点包以删除无效分发的警告?
- javascript - AutoComplete(MUI) 我正在尝试从 API 的复选框中设置默认值,但获取 (中间值).filter 不是函数错误
- angular - 如何在 Angular 12 中使用把手
- r - R根据列值将行从其他数据帧添加到数据帧
- python - 使用 python selenium 复制时遇到问题
- css - CSS:放置两个不同大小的元素,使中间正好在它们之间
- python - 在存储库的一段时间内获取所有观星者