LoginSignup
1
0

More than 3 years have passed since last update.

【pandas.DataFrame】継承したときに出る 【UserWarning: Pandas doesn't allow columns to be created】 の避け方

Last updated at Posted at 2020-05-01

pandas.DataFrameが便利なので、チョット応用したいときにクラス継承したりします。

インスタンス変数を定義


class ChildDataFrame(pd.DataFrame):
    def __init__(self, *args, **kwargs):
        super().__init__(pd.DataFrame(*args, **kwargs))
        instance = [1, 4, 6]


こうすればpandas.DataFrameにはないインスタンス変数やメソッドを定義できるわけです。

インスタンス変数呼び出し
>> > df = pd.DataFrame(np.random.randn(4, 5))
>> > cdf = ChildDataFrame(df)
>> > cdf.instance
[1, 4, 6]

しかしながらpandasは新しいインスタンス変数の追加を基本的に禁止しているそうです。
上のようにインスタンス変数定義すると、呼び出すたびにこんなワーニングがでます。

UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https: // pandas.pydata.org/pandas-docs/stable/indexing.html  # attribute-access
self.instance = [1, 4, 6]

インスタンス変数の代わりにクラス変数を使うとワーニングが抑えられるようです。

クラス変数を定義


class ChildDataFrame(pd.DataFrame):
    klass = [1, 4, 6]

    def __init__(self, *args, **kwargs):
        super().__init__(pd.DataFrame(*args, **kwargs))


インスタンス時に初期化したいときは、クラス変数を介してやるとワーニング無しにインスタンス変数のように扱えます。

クラス変数をインスタンス変数のように初期化


class ChildDataFrame(pd.DataFrame):
    klass = [1, 4, 6]

    def __init__(self, *args, **kwargs):
        super().__init__(pd.DataFrame(*args, **kwargs))
        ChildDataFrame.klass = ls


クラス変数をインスタンス変数のように初期化使い方
>> > df = pd.DataFrame(np.random.randn(4, 5))
>> > cdf = ChildDataFrame(df, [10, 20])
>> > cdf.klass
[10, 20]
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0