Reputation: 607
I have a dataframe like so:
df1:
col_1, col_2
a,1
b,2
c,3
d,4
And I'd like to concat df1 twice with the 2 columns swapping positions so that I have:
col_a, col_b
a,1
b,2
c,3
d,4
1,a
2,b
3,c
4,d
I tried:
df2 = pd.DataFrame(columns=['col_a','col_b'])
df2[['col_a','col_b']] = pd.concat([df1[['col_1','col_2]],df1[['col_2','col_1']]])
However, this just concats the dataframe against itself, so the result is:
col_a, col_b
a,1
b,2
c,3
d,4
a,1
b,2
c,3
d,4
What is the correct way to do this?
Upvotes: 0
Views: 80
Reputation: 323226
From numpy
pd.DataFrame(np.vstack([df.values,df.values[:,::-1]]),columns=df.columns)
Out[850]:
col_1 col_2
0 a 1
1 b 2
2 c 3
3 d 4
4 1 a
5 2 b
6 3 c
7 4 d
Upvotes: 0
Reputation: 59274
Using concat
x = pd.DataFrame(df.iloc[:, [1,0]].values, columns=df.columns)
pd.concat([df, x], sort=False)
col_1 col_2
0 a 1
1 b 2
2 c 3
3 d 4
0 1 a
1 2 b
2 3 c
3 4 d
Upvotes: 2