0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

numpyのobject型による参照の共有(アンチパターン)

Posted at

numpyでデフォルトの値をlist型に設定していると、設定用の変数が書き換わってしまうケースがあるようです。

設定用の変数: default_dict (before {'a':[]} -> after {'a':[hoge]} )

step1 データ作成

>>> import numpy as np
>>> import pandas as pd

>>> dtype = [('a','O')]
>>> default_dict = {'a':[]}

>>> arr = np.array(tuple(default_dict.values()),dtype=dtype)
>>> pd.DataFrame(arr)
    a
0  []

step2-1 データの変更

>>> arr['a'][0].append('hoge')
>>> pd.DataFrame(arr)
        a
0  [hoge]

1行目に対して処理を実行したつもりでも、2行目も変更されてしまう

step2-2

>>> # 元々のdefault_dict:  default_dict = {'a':[]}
>>> print(default_dict)
{'a': ['hoge']}

step2-1の処理によって、default_dictの値も変更されている

解決策1: copy.deepcopy

arr = np.array(copy.deepcopy([tuple(default_dict.values())]),dtype=dtype)

ソースコードの全て

import numpy as np
import pandas as pd
from IPython.display import display

dtype = [('a','O')]
default_dict = {'a':[]}

arr = np.array([tuple(default_dict.values())],dtype=dtype)
display(pd.DataFrame(arr))

arr['a'][0].append('hoge')
display(pd.DataFrame(arr))

print(default_dict)
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?