LoginSignup
12
11

More than 5 years have passed since last update.

Python / ループでリストやデータフレームを作成

Last updated at Posted at 2017-12-09

自分用のメモですが、少し検索した感じ日本語の記事はすぐには見つからなかったので、公開しておきます。ループでリストやデータフレームを作る方法です。stack overflowのこの質問に答えがありました。
stack ovreflow : Create multiple dataframes in loop

質問にあるように、安直に以下のようなループを回してもデータフレームはできません。(リストも同じ)

In[1]
import pandas as pd
list = ['a', 'b', 'c']
for i in list:
    i = pd.DataFrame()
print(a, b, c)
Out[1]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-8a28fab34b93> in <module>()
      3 for i in list:
      4     i = pd.DataFrame()
----> 5 print(a, b, c)

NameError: name 'a' is not defined

ということで、こういう場合下のように辞書に収める方法が良いらしいです。

In[2]
list = ['a', 'b', 'c']
d = {}
for i in list:
    d[i] = pd.DataFrame()
In[3]
for i, df in d.items():
    print(i, df)
Out[3]
a Empty DataFrame
Columns: []
Index: []
c Empty DataFrame
Columns: []
Index: []
b Empty DataFrame
Columns: []
Index: []

listの要素をキーとしてデータフレームができています。

参照はIn[3]のようにキーと値(データフレーム)を指定したループではシンプルにdfでよく、In[2]のようにキーだけのループになると、以下のような参照の仕方になります。

In[4]
for i in list:
    d[i]['column1'] = [1, 2, 3]
    print(i, d[i])
Out[4]
a    column1
0        1
1        2
2        3
b    column1
0        1
1        2
2        3
c    column1
0        1
1        2
2        3
12
11
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
12
11