タイトルの件について、pythonのdataframeの複数行の一括挿入についての質問です。
下記のような事を行っているのですが、dataframeを挿入する関数(insert_data_frame)の実行時間が12秒程度で10000回程度呼び出しされるため、実行速度に悩んでいます。
1000
そのため、start_indexとend_indexをリストとして格納して最終的に複数行を一括でoutput_DFに挿入できないかと考えたのですが、
方法が中々見つかりません。知っている方いれば教えてください。
・行っている事
1.数GB程度のinput_data.csvから特定条件の行をnp.whereでインデックスを抽出
2.抽出したインデックスが連続になっているか判定
3.連番でなくなった場合に、input_DFから対象となる範囲をoutput_DFに挿入
4.最終的なoutput_DFをlogとして出力
python
1#!/usr/bin/python3 2# -*- Coding: utf-8 -*- 3 4import pandas as pd 5import numpy as np 6 7 8# 2つのDFを結合、inputDF2のtarget_row行をinputDF1のinsert_row行に挿入する。 9def insert_data_frame(inputDF1, inputDF2, insert_row, target_row): 10 insert_data = pd.DataFrame([eval("inputDF2.iloc[{}]".format(target_row))], index=[insert_row]) 11 output_df = insert_data.combine_first(inputDF1) 12 13 return output_df 14 15 16def main(): 17 input_DF = pd.read_csv("input_data.csv") 18 output_DF = pd.DataFrame() 19 series_flg = 0 20 21 # 特定のインデックスを抽出 22 target_index = np.where(input_DF.ix[:, "test"] == 1) 23 24 for index in target_index[0]: 25 # 抽出したインデックスが連番か判定 26 if series_flg == 0: 27 start_index = index 28 end_index = index 29 series_flg = 1 30 31 elif (end_index + 1) == index: 32 end_index = index 33 34 # 連番でない場合は、出力用DFに挿入する 35 else: 36 if start_index == end_index: 37 output_DF = insert_data_frame(output_DF, input_DF, len(output_DF), str(start_index)) 38 else: 39 output_DF = insert_data_frame(output_DF, input_DF, len(output_DF), str(start_index) + ":" + str(end_index)) 40 41 # 抽出範囲を記載 42 output_DF.ix[len(output_DF), "start_index"] = start_index 43 output_DF.ix[len(output_DF), "end_index"] = end_index 44 45 start_index = index 46 end_index = index 47 48 output_DF.to_csv("output.csv") 49 50if __name__ == '__main__': 51 main() 52
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/10/07 12:13