我有一个包含 2 列的 [long] pandas 数据框。第一列是处方编号(请记住,这些不是唯一的,因为多行可以具有相同的处方编号)。第二列是该交易编号中的 1 项。我想为每个交易编号创建一个项目列表(删除重复项),并将这些列表中的每一个放入一个更大的嵌套列表中,其长度等于唯一交易编号的数量。
我已经成功实现了这一壮举,但是,它需要一段时间才能运行,我想知道更好(即更快)的方法。我的代码如下:
# get the unique values for prescription
list_prescription = list(pd.value_counts(df['prescription']).index)
# make a list of product_name for each tx_plan_id_date (this will be time consuming)
time_start = datetime.datetime.now()
counter = 1
list_list_product_name = []
for prescription in list_prescription:
# subset to just that tx_plan_id_date
df_subset = df[df['prescription'] == prescription]
# put product_name into a list
list_product_name = list(df_subset['product_name'])
# remove any duplicates
list_product_name = list(dict.fromkeys(list_product_name))
# append list_product_name to list_list_product_name
list_list_product_name.append(list_product_name)
# get current time
time_current = datetime.datetime.now()
# get minutes elapsed from time_start
time_elapsed = (time_current - time_start).seconds/60
# print a message to the console for status
stdout.write('\r{0}/{1}; {2:0.4f}% complete; elapsed time: {3:0.2} min.'.format(counter, len(list_prescription), (counter/len(list_prescription))*100, time_elapsed))
stdout.flush()
# increase counter by 1
counter += 1
请您参考如下方法:
你可以替换这部分
# put product_name into a list
list_product_name = list(df_subset['product_name'])
# remove any duplicates
list_product_name = list(dict.fromkeys(list_product_name))
# append list_product_name to list_list_product_name
list_list_product_name.append(list_product_name)
与
list_list_product_name.append(df_subset['product_name'].unique().tolist())
此外,您可能需要查看 groupby
