2017-05-25 3 views
1

Ich bin auf der Suche nach einem Weg in Pandas agg, um den Wert einer Spalte, basierend auf anderen Spaltenwert zu finden.Ergebnis in anderen Spalte mit Pandas Aggregation

Zum Beispiel: Ich habe folgende Datenrahmen

df = pd.DataFrame({"Project":['A','B','C','D','E'], 
        "Country" :['Brazil','Brazil','Germany','Germany','Argentina'],\ 
        "Value":[12,11,14,15,18]}) 

     Country Project Value 
0  Brazil  A  12 
1  Brazil  B  11 
2 Germany  C  14 
3 Germany  D  15 
4 Argentina  E  18 

ich diese Aggregation erstellt haben: würde neue Spalte auf diese Aggregation hinzuzufügen als Folge

aggregations = {'Project':{'Number of projects':'count'}, 
       'Value':{'Mean':'mean', 
         'Max':'max', 
         'Min':'min'}} 

df.groupby(['Country']).agg(aggregations) 

Ich möchte ein wich die Name des Projekts, das maximal 'Wert' wurde beobachtet. Das beabsichtigte Ergebnis wäre wie folgt:

    Project Value   
      Number of Projects Mean Max Min Projec_Max Projec_Min 
Country       
Argentina     1 18.0 18 18   E   E   
Brazil      2 11.5 12 11   A   B 
Germany      2 14.5 15 14   D   C 

Wie kann ich dies im Aggregation-Wörterbuch implementieren?

Vielen Dank im Voraus

Antwort

0

Nicht sicher, ob dies der beste Weg ist, aber es scheint zu funktionieren:

aggregations = {'Project':{'Number of projects':'count'}, 
       'Value':{'Mean':'mean', 
         'Max':'max', 
         'Min':'min', 
         'Project_Max': lambda x: df['Project'][x.idxmax()], 
         'Project_Min': lambda x: df['Project'][x.idxmin()]}} 
df.groupby(['Country']).agg(aggregations) 

Ergebnis:

   Value          Project 
      Project_Max Project_Min Max Mean Min Number of projects 
Country               
Argentina   E   E 18 18.0 18     1 
Brazil    A   B 12 11.5 11     2 
Germany    D   C 15 14.5 14     2 
+0

Danke, jdehesa. – Carlos

Verwandte Themen