2016-10-20 2 views
1
내가 정의한 다른 Series 서브 클래스의 숫자를 포함하는 DataFrame를 만들

한다. 그러나 DataFrame에 할당되면 서브 클래스는 Series에서 제거 된 것으로 보입니다.파이썬은 팬더 : 저장 시리즈 서브 클래스를 DataFrame 열

는 여기에 문제 설명하기 위해 장난감 예제 :이 문제는 이전에 #1713 제기되었을 수도 있습니다 본 적이

>>> import pandas as pd 
>>> class SeriesSubclass(pd.Series): 
...  @property 
...  def _constructor(self): 
...   return SeriesSubclass 
...  def times_two(self): 
...  """Method I need in this subclass.""" 
...   return self * 2 
... 
>>> subclass = SeriesSubclass([7, 8, 9]) 
>>> type(subclass)     # fine 
<class '__main__.SeriesSubclass'> 
>>> subclass.times_two()    # fine 
0 14 
1 16 
2 18 
dtype: int64 
>>> 
>>> data = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=list('ABC')) 
>>> data['D'] = subclass 
>>> type(data['D'])     # not good 
<class 'pandas.core.series.Series'> 
>>> data['D'].times_two()   # not good 
Traceback (most recent call last): 
    ... 
AttributeError: 'Series' object has no attribute 'times_two' 

을,하지만 난 실제 솔루션을 식별 할 수 있습니다. 거대한 도서관이기 때문에 다양한 PR, doc 버전 등을 따르기가 어렵습니다. 서브 클래 싱 역학은 내가 말할 수있는 한 잘 나타나지 않는 것 같습니다 (this seems to be it).

답변

0

자신 만의 pd.DataFrame 서브 클래스를 정의하지 않는 한 운이 나쁘다고 생각합니다. 그리고 그것은 훨씬 더 어려운 일이 될 것입니다.

df = pd.DataFrame() 
s = pd.Series([1, 2, 3]) 
s.random_attribute = 'hello!' 
print(s.random_attribute) 

df['A'] = s 
print(df.A.random_attribute) 

hello! 
--------------------------------------------------------------------------- 
AttributeError       Traceback (most recent call last) 
<ipython-input-273-e0031d933193> in <module>() 
     5 
     6 df['A'] = s 
----> 7 print(df.A.random_attribute) 

//anaconda/envs/3.5/lib/python3.5/site-packages/pandas/core/generic.py in __getattr__(self, name) 
    2742    if name in self._info_axis: 
    2743     return self[name] 
-> 2744    return object.__getattribute__(self, name) 
    2745 
    2746  def __setattr__(self, name, value): 

AttributeError: 'Series' object has no attribute 'random_attribute' 

df.As되지 않습니다 예를 고려해보십시오. df.As에서 생성되고 어떤 유형인지를 무시합니다.

0

비슷한 필요성을 가진 사람들을 위해 : DataFrame의 하위 클래스를 정의하고 __getitem__ 논리를 사용하는 것이 가장 좋은 해결책이라고 생각합니다.

내 원래 질문은 DataFrame이 기본적으로 컨테이너가 아닌 것으로 가정된다는 가정하에 작성되었습니다. 그것은 Series의 서브 클래스로 열을 검색하기 위해, ... 예컨대, 따라서

>>> from pandas import Series, DataFrame 
>>> s = Series([1, 2, 3, 4], name='x') 
>>> df = DataFrame(s) 
>>> s is df.x 
False 

보다 동적, 당신은 __getitem__으로 수리를해야합니다.

나는 예로서 역할을 할 수있는, 내 자신의 패키지에서 이것을 구현 : https://github.com/jmackie4/activityio/blob/master/activityio/_util/types.py

내가 더 우아한 솔루션을 사람에서하지만 듣고 싶어 할 것입니다!