有效地检查与Pandas DataFrame中的某些值匹配的行,并将其添加到另一个数据帧

时间:2017-06-23 14:44:11

标签: python pandas dataframe

我有一个数据框(称为:data),其中包含客户及其购买的列表 - 如下所示:

ID product 1 orange 1 banana 2 apple 2 orange 2 banana 3 banana 3 apple 4 apple 5 apple 5 orange 5 banana 我想要做的是生成一个矩阵,其中索引是客户的ID和作为产品的列,如果客户购买产品,则填充矩阵为1或者如果他没有,则填充0。最终矩阵将如下所示:

enter image description here

我已经做到了但是花了很长时间才开始处理大约20,000名拥有3,000多种产品的客户(预计完成的时间大约是4天!)。

这是我的代码:

df_matrix = pd.DataFrame(index = customers, columns = products)
for indx in df_matrix.index:
    for col in df_matrix.columns:
        if ((data['ID'] == indx) & (data['product'] == col)).any() == True:
            df_matrix.loc[indx,col] = 1

1 个答案:

答案 0 :(得分:3)