向Pandas.Series添加自定义属性
原学程将引见向Pandas.Series添减自界说属性的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。
成绩描写
我正在测验考试向pd.DataFrame内的每一个pd.Series添减1个自界说属性。详细天说,我获得了1个CSV,个中间歇性天将色彩代码嵌进到列题目中。我愿望在画制图表之前将这些实质事后处置成1个属性,并将默许色彩分派给其余未指定的列。
但是在其焦点部门,我只须要在Series中的某个地位添减1个定制属性,便像您在所有其余Python对于象上能够做的这样。简化示例:
>>> import pandas as pd
>>> df = pd.DataFrame({"Low":[一,二,三], "Medium":[四,五,六], "High":[七,8,九]})
>>> s一 = df.iloc[:,一]
>>>
>>> s一.color = 'yellow'
>>> print(s一.color)
yellow
>>>
>>> type(s一)
<class 'pandas.core.series.Series'>
>>>
>>> ### assign back to the DataFrame...
>>> df.iloc[:,一] = s一
>>>
>>> print(df.iloc[:,一].color)
Traceback (most recent call last):
File "<stdin>", line 一, in <module>
File "/Library/Frameworks/Python.framework/Versions/三.九/lib/python三.九/site-packages/pandas/core/generic.py", line 五四8七, 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[:,一], 'color', 'yellow')
>>>
>>> ### goes in ok, but...
>>> df.iloc[:,一].color
Traceback (most recent call last):
File "<stdin>", line 一, in <module>
File "/Library/Frameworks/Python.framework/Versions/三.九/lib/python三.九/site-packages/pandas/core/generic.py", line 五四8七, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'Series' object has no attribute 'color'
>>>
明显, pandas 不只仅是传播指针。我没有须要序列化,但是我确切须要该属性在运转时函数之间传播。
我没有想只为1个属性对于全部数据帧/系列模子停止子类化。厌倦了这1面,我对准了DataFrame的包装类,它保存了色彩以及系列索引之间的属性映照,然则...再说1次,在1个python对于象上应用+一属性仿佛有些凌乱。
对于最简略/最清洁的处理计划有甚么设法主意?
推举谜底
我想我在相似成绩中的answer能够会对于您有所赞助。我以为您须要1个custom属性拜访器去扩大 pandas 系列
佳了闭于向Pandas.Series添减自界说属性的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。