python - Pandas: concat sorted dfs with same labels -


i have 3 dfs in list. each df has same rows order of these rows not same. sorted on value.

i concat these dfs fails because order of row labels dont match.

my 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 

here how try concat:

pd.concat(listofdfs, axis=1) 

is there way concat these dfs without sorting them? thought concat didn't care positioning of labels each df contained same labels?

i think bug, maybe similar 6963.

for me work sort_index of 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 

error if sort_index omited:

valueerror: shape of passed values (3, 4), indices imply (3, 3)

it seems concat use unique indexes, if indexes not sorted, see bellow:

if indexes replaced numbers:

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 

but if sort_index omited:

invalidindexerror: reindexing valid uniquely valued index objects


Comments