私はPythonの初心者ですが、このコードをより速く実行できるかどうかを知りたいので、私の無知を許してください。私は2つのExcelシートを持っています:1つ(結果)は、約30,000行の一意のユーザーIDを持っています。そして、質問された30列の質問があり、その下のセルは空です。私の2番目のシート(はと答えています)には、約400,000行と3つの列があります。最初の列にはユーザーIDがあり、2番目には尋ねられた質問があり、3番目にはユーザーからのそれぞれの質問に対する回答があります。私がしたいのは基本的にインデックス・マッチ・アレイ・エクセル関数です。ユーザーIDと質問を照合して、シート1の空白セルにシート2の答えを記入することができます。2番目の配列から複数の条件に一致するPython配列をループする、高速メソッド?
今私は、コードの一部を書いたが、それを行うための私の方法を取っていない場合、それは私が把握しようとしているだけのシート1から4列を処理するのに約2時間を要しましたNumpyの機能を完全に活用できます。
import pandas as pd
import numpy as np
# Need to take in data from 'answers' and merge it into the 'results' data
# Will requiring matching the data based on 'id' in column 1 of 'answers' and the
# 'question' in column 2 of 'answers'
results = pd.read_excel("/Users/data.xlsx", 'Results')
answers = pd.read_excel("/Users/data.xlsx", 'Answers')
answers_array = np.array(answers) #########
# Create a list of questions being asked that will be matched to column 2 in answers.
# Just getting all the questions I want
column_headers = list(results.columns)
formula_headers = [] #########
for header in column_headers:
formula_headers.append(header)
del formula_headers[0:13]
# Create an empty array with ids in which the 'merged' data will be fed into
pre_ids = np.array(results['Id'])
ids = np.reshape(pre_ids, (pre_ids.shape[0], 1))
ids = ids.astype(str)
zero_array = np.zeros((ids.shape[0], len(formula_headers)))
ids_array = np.hstack((ids, zero_array)) ##########
for header in range(len(formula_headers)):
question_index = formula_headers[header]
for user in range(ids_array.shape[0]):
user_index = ids_array[user, 0]
location = answers_array[(answers_array[:, 0] == int(user_index)) & (answers_array[:, 1] == question_index)]
# This location formula is what I feel is messing everything up,
# or could be because of the nested loops
# If can't find the user id and question in the answers array
if location.size == 0:
ids_array[user][header + 1] = ''
else:
row_location_1 = np.where(np.all(answers_array == location[0], axis=1))
row_location = int(row_location_1[0][0])
ids_array[user][header + 1] = answers_array[row_location][2]
print ids_array
うーん問題を複製している場合は、あなたが
reindex_like
方法を追加することができますがつまり、回答シートの列1には、各質問の答えを示すためにユーザーIDが重複しています。 –
@MiriamAlhはい、それは私が 'id'にインデックスを設定した理由です「質問」 – piRSquared
@MiriamAlh私が実証できるサンプルデータがありますか?私が見ることができないデータセットについて話すことは非常に難しいです。 – piRSquared