向Pandas.Series添加自定义属性 [英] Add custom attribute to Pandas.Series

查看:0
本文介绍了向Pandas.Series添加自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

但在其核心部分,我只需要在Series中的某个位置添加一个定制属性,就像您在任何其他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 不仅仅是传递指针。我不需要序列化,但我确实需要该属性在运行时函数之间传递。

我不想只为一个属性对整个数据帧/系列模型进行子类化。厌倦了这一点,我瞄准了DataFrame的包装类,它存储了颜色和系列索引之间的属性映射,但是...再说一次,在一个python对象上使用+1属性似乎有些混乱。

对最简单/最干净的解决方案有什么想法?

推荐答案

我想我在类似问题中的answer可能会对您有所帮助。我认为您需要一个custom属性访问器来扩展 pandas 系列

这篇关于向Pandas.Series添加自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆