2016-04-06 15 views
1

diese Daten Gegeben:Pandas: Schwenken auf Rang

pd.DataFrame({'id':['aaa','aaa','abb','abb','abb','acd','acd','acd'], 
       'loc':['US','UK','FR','US','IN','US','CN','CN']}) 

    id loc 
0 aaa US 
1 aaa UK 
2 abb FR 
3 abb US 
4 abb IN 
5 acd US 
6 acd CN 
7 acd CN 

Wie kann ich es so weit schwenken:

id loc1 loc2 loc3 
aaa US  UK  None 
abb FR  US  IN 
acd US  CN  CN 

ich für die meisten idiomatische Methode suchen.

Antwort

2

Ich glaube, Sie neue Spalte cols mit groupby erstellen können, cumcount und konvertieren string von astype, letzte Verwendung pivot:

df['cols'] = 'loc' + (df.groupby('id')['id'].cumcount() + 1).astype(str) 
print df 
    id loc cols 
0 aaa US loc1 
1 aaa UK loc2 
2 abb FR loc1 
3 abb US loc2 
4 abb IN loc3 
5 acd US loc1 
6 acd CN loc2 
7 acd CN loc3 

print df.pivot(index='id', columns='cols', values='loc') 
cols loc1 loc2 loc3 
id     
aaa US UK None 
abb FR US IN 
acd US CN CN 

Wenn Sie entfernen möchten Index und Spaltennamen rename_axis verwenden:

print df.pivot(index='id', columns='cols', values='loc').rename_axis(None) 
                 .rename_axis(None, axis=1) 
    loc1 loc2 loc3 
aaa US UK None 
abb FR US IN 
acd US CN CN 

Alles zusammen, danke Colin:

print pd.pivot(df['id'], 'loc' + (df.groupby('id').cumcount() + 1).astype(str), df['loc']) 
     .rename_axis(None) 
     .rename_axis(None, axis=1) 

    loc1 loc2 loc3 
aaa US UK None 
abb FR US IN 
acd US CN CN  

Ich versuche rank, aber ich habe Fehler in Version 0.18.0:

print df.groupby('id')['loc'].transform(lambda x: x.rank(method='first')) 
#ValueError: first not supported for non-numeric data 
+1

Dies ist eine gute Antwort. Vereinfacht es leicht: 'pd.pivot (df ['id'], 'loc' + (df.groupby ('id'). Cumcount() + 1) .asyp (str), df ['loc'])' – Colin

+0

Super Idee, danke. – jezrael

+0

großartige Lösung, aber ich renne in [ein Problem] (http://stackoverflow.com/questions/36456857/pandas-index-join-level-on-non-unique-index-is-not-implementiert) anwenden es zu echten Daten. –