2017-06-13 5 views
0

J'ai un dataframe qui ressemble à ceci:Remodelage Pandas dataframe pour Fusion et publipostage dans Word

Customer ID  Invoice ID Invoice Total Customer Total 
8063863   110100456  41,47   248,82 
8063863   110100677  41,47   248,82 
8063863   110100838  41,47   248,82 
8063863   110101106  41,47   248,82 
8063863   110101259  41,47   248,82 
8063863   110101401  41,47   248,82 

Ce que je voudrais avoir quelque chose comme ceci:

Customer ID Invoice_1 Invoice_Total_1 Invoice_2 Invoice_Total_2 ... Customer_Total 
8063863  110100456    41,47 110100677    41,47   248,82 

I'D Comme pour ensuite exporter la Dataframe à CSV et l'utiliser dans Word pour Mail Fusionner les différents clients leur résumé.

J'ai ajouté le total client dans Pandas en utilisant pivot_table mais je suis bloqué sur l'aplatissement de la Dataframe.

+0

espoir ce lien peut aider https://stackoverflow.com/questions/34641615/concatenate-multiple-rows-to-one- single-in-pandas – Wen

+0

Merci! Je vais vérifier ça. Fondre et empiler pour encadrer devrait faire l'affaire en quelque sorte. Je verrai si je peux obtenir ceci pour fonctionner avec un seul identifiant de client unique et multiple. –

Répondre

1

Essayons:

def f(x): 
    n,i = pd.factorize(x['Invoice ID']) 
    df1 = pd.DataFrame([x.loc[(x['Invoice ID']==i.values),'Invoice Total'].values], columns=(n+1).astype(str)).add_prefix('Invoice_Total_') 
    df2 = pd.DataFrame([i.values],columns=(n+1).astype(str)).add_prefix('Invoice_') 
    return pd.concat([df1,df2],axis=1).assign(Customer_Total=x['Customer Total'].max()),drop=True) 

df_out = df.groupby('Customer ID').apply(f).reset_index(-1,drop=True) 

Sortie:

  Invoice_Total_1 Invoice_Total_2 Invoice_Total_3 Invoice_Total_4 \ 
Customer ID                 
8063863    41,47   41,47   41,47   41,47 

      Invoice_Total_5 Invoice_Total_6 Invoice_1 Invoice_2 Invoice_3 \ 
Customer ID                  
8063863    41,47   41,47 110100456 110100677 110100838 

      Invoice_4 Invoice_5 Invoice_6 Customer_Total 
Customer ID             
8063863  110101106 110101259 110101401   248,82 
+0

Merci pour la réponse, fonctionne magnifiquement. Je dois vraiment intensifier ma compréhension des pandas –

+0

Vous êtes les bienvenus. –