23
8

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 3 years have passed since last update.

Pandas DataFrame で append すると遅い

Last updated at Posted at 2019-05-07
  • いつも DataFrameにpd.Series を append していたのですが、遅くて遅くて困っていました。
    Goggle で検索しようとすると、"pandas dataframe append very slow"というキーワードが候補に出てきました。
  • 作戦として、dictionary を作って、from_dict(my_dic, orinet="index")とする方法があるようで、こちらの方が早い。
  • 下記のコードの場合、append では5.7秒、from_dict では 0.02秒でした。圧倒的な差。
check_df_append_time.py
import pandas as pd
import numpy as np
import time

N=10000

def gen_df1(N):
    df = pd.DataFrame(index=[], columns=["X","Y"])
    for i in range(0, N):
        df = df.append(pd.Series([np.random.randn(),np.random.randn()], index=df.columns),
                         ignore_index=True)
    return df

t1 = time.time()
df1 = gen_df1(N)
print(df1.describe())
elapsed_time = time.time() - t1
print(f"elapsed time {elapsed_time} [s]")

def gen_df2(N):
    temp_dict = {}
    for i in range(0,N):
        temp_dict[i] = [np.random.randn(), np.random.randn()]
    df = pd.DataFrame.from_dict(temp_dict, orient='index')
    return df

t1 = time.time()
df2 = gen_df2(N)
print(df2.describe())
elapsed_time = time.time() - t1
print(f"elapsed time {elapsed_time} [s]")
23
8
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
23
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?