Ivan
Ivan

Reputation: 20101

Concatenate two pandas dataframe with the same index but on different positions

I have a data frame like

id    value_right    color_right     value_left   color_left
1      asd           red              dfs         blue
2      dfs           blue             afd         green
3      ccd           yellow           asd         blue
4      hty           red              hrr         red

I need to get the left values below the right values, something like

id    value          color
1      asd           red        
1      dfs           blue
2      dfs           blue
2      afd           green
3      ccd           yellow
3      asd           blue
4      hty           red
4      hrr           red

I tried to split in two data frames and to interleave using the id, but I got only half of the data on it, using the mod of the value of the id. Any ideas?

Upvotes: 2

Views: 291

Answers (1)

EdChum
EdChum

Reputation: 393963

Take a view of the desired left and right side dfs, then rename the columns and then concat them and sort on 'id' column:

In [205]:
left = df[['id','value_left','color_left']].rename(columns={'value_left':'value','color_left':'color'})
right = df[['id','value_right','color_right']].rename(columns={'value_right':'value','color_right':'color'})
merged = pd.concat([right,left]).sort('id')
merged

Out[205]:
   id value   color
0   1   asd     red
0   1   dfs    blue
1   2   dfs    blue
1   2   afd   green
2   3   ccd  yellow
2   3   asd    blue
3   4   hty     red
3   4   hrr     red

Upvotes: 2

Related Questions