好的。做了一些工作,但我做到了。希望能幫助到你。
import pandas as pd
import numpy as np
from itertools import combinations
df = pd.DataFrame([], columns=['CustomerName','Order Sequence','Category'])
df['CustomerName'] = [1,1,1,1,1,1,1,2,2,2,3,3,3,3]
df['Order Sequence'] = [1,2,2,2,3,3,3,1,2,3,1,1,2,3]
df['Category'] = ['Food','Food','Clothes','Furniture','Clothes','Food','Toys','Clothes','Toys','Food','Furniture','Toys','Food','Food']
df2 = pd.DataFrame([], columns=['CustomerName','Category1','Category2','Category3'])
for CN in sorted(set(df['CustomerName'])):
df_temp = pd.DataFrame([], columns=['CustomerName','Category1','Category2','Category3'])
list_OS_1 = []
list_OS_2 = []
list_OS_3 = []
MMC = reduce(lambda x, y: x*y,df.loc[df['CustomerName']==CN, 'Order Sequence'].value_counts().values)
for N in np.arange(MMC/len(df.loc[((df['CustomerName']==CN) & (df['Order Sequence']==1)), 'Category'])):
for CTG in df.loc[((df['CustomerName']==CN) & (df['Order Sequence']==1)), 'Category']:
list_OS_1.append(CTG)
for N in np.arange(MMC/len(df.loc[((df['CustomerName']==CN) & (df['Order Sequence']==2)), 'Category'])):
for CTG in df.loc[((df['CustomerName']==CN) & (df['Order Sequence']==2)), 'Category']:
list_OS_2.append(CTG)
for N in np.arange(MMC/len(df.loc[((df['CustomerName']==CN) & (df['Order Sequence']==3)), 'Category'])):
for CTG in df.loc[((df['CustomerName']==CN) & (df['Order Sequence']==3)), 'Category']:
list_OS_3.append(CTG)
df_temp['Category1'] = list_OS_1
df_temp['Category2'] = list_OS_2
df_temp['Category3'] = list_OS_3
df_temp['CustomerName'] = CN
df2 = pd.concat([df2,df_temp],0)
print (df2)
輸出:
CustomerName Category1 Category2 Category3
0 1.0 Food Food Clothes
1 1.0 Food Clothes Food
2 1.0 Food Furniture Toys
3 1.0 Food Food Clothes
4 1.0 Food Clothes Food
5 1.0 Food Furniture Toys
6 1.0 Food Food Clothes
7 1.0 Food Clothes Food
8 1.0 Food Furniture Toys
0 2.0 Clothes Toys Food
0 3.0 Furniture Food Food
1 3.0 Toys Food Food
PS:它不是DINAMIC,因此,如果您添加或刪除它會得到fcked了類別。 但只要它遵循你從我身邊走過最初的標準,它SHLD工作
這是一個排列?爲什麼顧客1只能在他的第一個訂單中訂購食物? –
歡迎來到Stack Overflow!您可以先[參觀](http://stackoverflow.com/tour)並學習[如何提出一個好問題](http://stackoverflow.com/help/how-to-ask)並創建一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例。這使我們更容易幫助你。 –
@PauloMiraMor - 不,它可能是任何東西。他本可以先購買衣服,傢俱或兩者。是的,需要按每個客戶的訂單順序排列所有產品 – Tanya