Consider the following DataFrames df :
df =
kind A B
names u1 u2 u3 y1 y2
Time
0.0 0.5083 0.1007 0.8001 0.7373 0.1387
0.1 0.6748 0.0354 0.0076 0.8421 0.2670
0.2 0.1753 0.1013 0.5231 0.8060 0.0040
0.3 0.5953 0.6505 0.7127 0.0771 0.1023
0.4 0.4409 0.0193 0.6765 0.9800 0.0715
and df1:
df1 =
kind A
names potato
Time
0.0 0.4043
0.1 0.9801
0.2 0.1298
0.3 0.9564
0.4 0.4409
I want to concatenate the two DataFrames such that the resulting DataFrame is:
df2 =
kind A B
names u1 u2 u3 potato y1 y2
Time
0.0 0.5083 0.1007 0.8001 0.5083 0.7373 0.1387
0.1 0.6748 0.0354 0.0076 0.6748 0.8421 0.2670
0.2 0.1753 0.1013 0.5231 0.1753 0.8060 0.0040
0.3 0.5953 0.6505 0.7127 0.5953 0.0771 0.1023
0.4 0.4409 0.0193 0.6765 0.4409 0.9800 0.0715
What I run is pandas.concat([df1, df2, axis=1).sort_index(level="kind", axis=1) but that results in
kind A B
names potato u1 u2 u3 y1 y2
Time
0.0 0.4043 0.5083 0.1007 0.8001 0.7373 0.1387
0.1 0.9801 0.6748 0.0354 0.0076 0.8421 0.2670
0.2 0.1298 0.1753 0.1013 0.5231 0.8060 0.0040
0.3 0.9564 0.5953 0.6505 0.7127 0.0771 0.1023
0.4 0.4409 0.4409 0.0193 0.6765 0.9800 0.0715
i.e. the column potato is appended at the beginning of df["A"] whereas I want it appended to the end.
>Solution :
Add parameter sort_remaining=False in DataFrame.sort_index:
df = pd.concat([df1, df2], axis=1).sort_index(level="kind", axis=1, sort_remaining=False)
print (df)
kind A B
names u1 u2 u3 potato y1 y2
Time
0.0 0.5083 0.1007 0.8001 0.4043 0.7373 0.1387
0.1 0.6748 0.0354 0.0076 0.9801 0.8421 0.2670
0.2 0.1753 0.1013 0.5231 0.1298 0.8060 0.0040
0.3 0.5953 0.6505 0.7127 0.9564 0.0771 0.1023
0.4 0.4409 0.0193 0.6765 0.4409 0.9800 0.0715