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