- いつも 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]")