2016-04-06 6 views
0

Ich habe 3 dfs in einer Liste. Jedes df hat die gleichen Zeilen, aber die Reihenfolge dieser Zeilen ist nicht gleich. Sie sind nach Wert sortiert.Pandas: concat sortierte dfs mit gleichen Labels

Ich möchte diese dfs zusammen concat, aber es schlägt fehl, weil die Reihenfolge der Zeilenbeschriftungen nicht übereinstimmen.

mein dfs:

 Total   Total   Total 
    sony 5  hond 9  phon 6 
    hond 6  sony 3  phon 3 
    phon 8  phon 4  hond 2 
    phon 3  phon 5  sony 8 

Hier wie concat versuchen:

pd.concat(listofdfs, axis=1) 

ist es eine Möglichkeit, diese dfs zu verketten, ohne sie zu Sortieranlagen? Ich dachte, concat kümmerte sich nicht um die Positionierung von Etiketten, da jedes df die gleichen Etiketten enthielt?

+0

Pass 'ignore_index = true'' pd.concat (listofdfs, Achse = 1, ignore_index = True) 'sollte – EdChum

+0

arbeiten Ich erhalte diesen Fehler: ValueError: Die Form der übergebenen Werte ist (6, 15), Indizes implizieren (6, 14). Concat funktioniert jedoch gut, wenn ich jedes df sortiere. –

+0

Wollen Sie also wiederholt "beitreten"? – EdChum

Antwort

1

Ich denke, es ist ein Fehler, vielleicht etwas ähnliches 6963.

Für mich sort_index aller Arbeit DataFrames:

df1 = pd.DataFrame({'Total': {'sony': 5, 'phon': 3, 'hond': 6}}) 
df2 = pd.DataFrame({'Total': {'hond': 9, 'phon': 5, 'sony': 3}}) 
df3 = pd.DataFrame({'Total': {'hond': 2, 'sony': 8, 'phon': 3}}) 

df1 = df1.sort_index() 
df2 = df2.sort_index() 
df3 = df3.sort_index() 

listofdfs = [df1,df2,df3] 

print pd.concat(listofdfs, axis=1) 
     Total Total Total 
hond  6  9  2 
phon  8  4  6 
phon  3  5  3 
sony  5  3  8 

Fehler, wenn sort_index ist omited:

ValueError: Shape of passed values is (3, 4), indices imply (3, 3)

Es scheint concat Verwendung unique Indizes, wenn Indizes nicht sortiert werden, siehe unten:

Wenn indexes werden durch numbers ersetzt:

df1 = pd.DataFrame({'Total': {1: 5, 2: 6, 3: 3}}) 
df2 = pd.DataFrame({'Total': {1: 3, 2: 9, 3: 5}}) 
df3 = pd.DataFrame({'Total': {1: 8, 2: 2, 3: 3}}) 

print df1 
print df2 
print df3 
    Total 
1  5 
2  6 
3  8 
3  3 
    Total 
2  9 
1  3 
3  4 
3  5 
    Total 
3  6 
3  3 
2  2 
1  8 

df1 = df1.sort_index() 
df2 = df2.sort_index() 
df3 = df3.sort_index() 

listofdfs = [df1,df2,df3] 

print pd.concat(listofdfs, axis=1) 
    Total Total Total 
1  5  3  8 
2  6  9  2 
3  8  4  6 
3  3  5  3 

Aber wenn sort_index ist omited:

InvalidIndexError: Reindexing only valid with uniquely valued Index objects