回答編集履歴

1

計測結果を追記

2018/02/21 12:57

投稿

退会済みユーザー
test CHANGED
@@ -77,3 +77,141 @@
77
77
  ```
78
78
 
79
79
  ご参考までに。
80
+
81
+
82
+
83
+ --------
84
+
85
+ 追記
86
+
87
+ 速度を測ってみました。結論から言うと、1回の検索ですらpandasのほうが平均して遅いという結果になりました。
88
+
89
+
90
+
91
+ 適当にデータを作成
92
+
93
+ ```Python
94
+
95
+ import pandas as pd
96
+
97
+ from itertools import product
98
+
99
+ temp = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
100
+
101
+ test_dict = {s+t+u: [s+t+u+"0", s+t+u+"1", s+t+u+"2"] for s, t, u in product(temp, repeat=3)}
102
+
103
+ df = pd.DataFrame.from_dict(test_dict, orient="index")
104
+
105
+ print("head")
106
+
107
+ print(df.head())
108
+
109
+ print("tail")
110
+
111
+ print(df.tail())
112
+
113
+ print("レコード数", len(df))
114
+
115
+
116
+
117
+ # head
118
+
119
+ # 0 1 2
120
+
121
+ # aaa aaa0 aaa1 aaa2
122
+
123
+ # aab aab0 aab1 aab2
124
+
125
+ # aac aac0 aac1 aac2
126
+
127
+ # aad aad0 aad1 aad2
128
+
129
+ # aae aae0 aae1 aae2
130
+
131
+ # tail
132
+
133
+ # 0 1 2
134
+
135
+ # ZZV ZZV0 ZZV1 ZZV2
136
+
137
+ # ZZW ZZW0 ZZW1 ZZW2
138
+
139
+ # ZZX ZZX0 ZZX1 ZZX2
140
+
141
+ # ZZY ZZY0 ZZY1 ZZY2
142
+
143
+ # ZZZ ZZZ0 ZZZ1 ZZZ2
144
+
145
+ # レコード数 140608
146
+
147
+ ```
148
+
149
+
150
+
151
+ これに対して元の方法とpandasを比較します。
152
+
153
+ ```Python
154
+
155
+ def get_value0(index, target):
156
+
157
+ # 元の方法
158
+
159
+ for key, value in test_dict.items():
160
+
161
+ if target == value[index]:
162
+
163
+ return value
164
+
165
+
166
+
167
+ def get_value1(index, target):
168
+
169
+ # pandas使った方法
170
+
171
+ return df[df[index] == target].values.tolist()[0]
172
+
173
+
174
+
175
+ # 探したいデータ
176
+
177
+ index = 2 # 取得したい値のインデックス
178
+
179
+ target = "Gcw2" # 取得したい値
180
+
181
+
182
+
183
+ # 同じ結果になるか確認
184
+
185
+ assert get_value0(index, target) == get_value1(index, target)
186
+
187
+
188
+
189
+ # 元の方法
190
+
191
+ %timeit get_value0(index, target)
192
+
193
+ # 7.78 ms ± 131 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
194
+
195
+
196
+
197
+ # pandasを使った方法
198
+
199
+ %timeit get_value1(index, target)
200
+
201
+ # 11.7 ms ± 231 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
202
+
203
+ ```
204
+
205
+
206
+
207
+ targetによっては元の方法では最後までloopを回さないとダメなにで、パフォーマンスにムラがあります。ただ、ワーストケースでpandasより1ms遅い程度でした。
208
+
209
+
210
+
211
+ 実行環境
212
+
213
+ Python 3.6.4
214
+
215
+ pandas==0.22.0
216
+
217
+ MBP