質問するログイン新規登録

回答編集履歴

1

計測結果を追記

2018/02/21 12:57

投稿

退会済みユーザー
answer CHANGED
@@ -37,4 +37,73 @@
37
37
  print(value)
38
38
  # ['X', 'Y', 'Z']
39
39
  ```
40
- ご参考までに。
40
+ ご参考までに。
41
+
42
+ --------
43
+ 追記
44
+ 速度を測ってみました。結論から言うと、1回の検索ですらpandasのほうが平均して遅いという結果になりました。
45
+
46
+ 適当にデータを作成
47
+ ```Python
48
+ import pandas as pd
49
+ from itertools import product
50
+ temp = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
51
+ 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)}
52
+ df = pd.DataFrame.from_dict(test_dict, orient="index")
53
+ print("head")
54
+ print(df.head())
55
+ print("tail")
56
+ print(df.tail())
57
+ print("レコード数", len(df))
58
+
59
+ # head
60
+ # 0 1 2
61
+ # aaa aaa0 aaa1 aaa2
62
+ # aab aab0 aab1 aab2
63
+ # aac aac0 aac1 aac2
64
+ # aad aad0 aad1 aad2
65
+ # aae aae0 aae1 aae2
66
+ # tail
67
+ # 0 1 2
68
+ # ZZV ZZV0 ZZV1 ZZV2
69
+ # ZZW ZZW0 ZZW1 ZZW2
70
+ # ZZX ZZX0 ZZX1 ZZX2
71
+ # ZZY ZZY0 ZZY1 ZZY2
72
+ # ZZZ ZZZ0 ZZZ1 ZZZ2
73
+ # レコード数 140608
74
+ ```
75
+
76
+ これに対して元の方法とpandasを比較します。
77
+ ```Python
78
+ def get_value0(index, target):
79
+ # 元の方法
80
+ for key, value in test_dict.items():
81
+ if target == value[index]:
82
+ return value
83
+
84
+ def get_value1(index, target):
85
+ # pandas使った方法
86
+ return df[df[index] == target].values.tolist()[0]
87
+
88
+ # 探したいデータ
89
+ index = 2 # 取得したい値のインデックス
90
+ target = "Gcw2" # 取得したい値
91
+
92
+ # 同じ結果になるか確認
93
+ assert get_value0(index, target) == get_value1(index, target)
94
+
95
+ # 元の方法
96
+ %timeit get_value0(index, target)
97
+ # 7.78 ms ± 131 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
98
+
99
+ # pandasを使った方法
100
+ %timeit get_value1(index, target)
101
+ # 11.7 ms ± 231 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
102
+ ```
103
+
104
+ targetによっては元の方法では最後までloopを回さないとダメなにで、パフォーマンスにムラがあります。ただ、ワーストケースでpandasより1ms遅い程度でした。
105
+
106
+ 実行環境
107
+ Python 3.6.4
108
+ pandas==0.22.0
109
+ MBP