【发布时间】:2017-09-09 19:38:40
【问题描述】:
我是 Python 的初学者,想知道是否有更快的方法来编写此代码,所以请原谅我的无知。我有 2 张 excel 表格:一张(results)有大约 30,000 行唯一用户 ID,然后我有 30 列问题被问到,下面的单元格是空的。我的第二张表(answers)有大约 400,000 行和 3 列。第一列是用户 ID,第二列是提出的问题,第三列是用户对每个相应问题的答案。我想要做的本质上是一个索引匹配数组 excel 函数,我可以通过匹配用户 ID 和所问的问题来填充表 1 中的空白单元格和表 2 中的答案。
现在我编写了一段代码,但仅处理工作表 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
【问题讨论】:
标签: python arrays excel pandas numpy