LoginSignup
3
4

More than 5 years have passed since last update.

【Python】pandas.DataFrameとnumpy.ndarrayのループ時間比較

Last updated at Posted at 2016-07-10

データ分析の際にpandas.DataFrameで苦肉の策としてforループさせると時間がかかり過ぎることがあるため,numpy.ndarrayにするとどのくらい速くなるか確認。

check_speed.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import time
import numpy as np
import pandas as pd

df100 = pd.DataFrame(np.random.randn(100, 100))
df1000 = pd.DataFrame(np.random.randn(1000, 1000))

# 100 * 100で計測
print('Time of pandas.DataFrame (100 * 100)')
idxs = df100.index
cols = df100.columns
start = time.time() # ここから
for idx in idxs:
    for col in cols:
        df100.ix[idx, col] = df100.ix[idx, col] + 1
print(time.time() - start) # ここまで

print('Time of numpy.ndarray (100 * 100)')
matrix = df100.values
idx_range = range(len(df100.values[:, 0]))
col_range = range(len(df100.values[0, :]))
start = time.time() # ここから
for i in idx_range:
    for j in col_range:
        matrix[i, j] = matrix[i, j] + 1
print(time.time() - start) # ここまで

# 1000 * 1000で計測
print('Time of pandas.DataFrame (1000 * 1000)')
idxs = df1000.index
cols = df1000.columns
start = time.time() # ここから
for idx in idxs:
    for col in cols:
        df1000.ix[idx, col] = df1000.ix[idx, col] + 1
print(time.time() - start) # ここまで

print('Time of numpy.ndarray (1000 * 1000)')
matrix = df1000.values
idx_range = range(len(df1000.values[:, 0]))
col_range = range(len(df1000.values[0, :]))
start = time.time() # ここから
for i in idx_range:
    for j in col_range:
        matrix[i, j] = matrix[i, j] + 1
print(time.time() - start) # ここまで

計測結果は以下。

種別 100×100[秒] 1000×1000[秒]
pandas.DataFrame 2.010 206.6285
numpy.ndarray 0.0055 0.5832

思っていたより差がありますね。今後はちゃんとnumpy.ndarrayで計算するようにしないと...。
あと,計算時間は概ね行列のサイズに比例するようです。

3
4
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
3
4