Reorganize elements of Pandas Dataframe by row and column to new dataframe

Viewed 55

i do have the following Dataframe:

    1    2    3      4      5      6
0  NaN  NaN  NaN     a      b     c
1  NaN  NaN  NaN     d      e     f
2  NaN  NaN  NaN     g      h     i
0  1.0  2.0 3.0   -5.0   -4.0  -36.0
1  4.0  5.0 6.0  -32.0  -31.0 -120.0
2  7.0  8.0 9.0  102.0  126.0    3.0

This is a product of four Dataframes, so each quarter (size 3x3) is also available as a isolated pandas dataframe. I need a Dataframe structured like this:

     1  2  3  4  5  6   
1    1  a  2  d  3  g  
2    4  b  5  e  6  h  
3    7  c  8  f  9  i
       

described in Words:

so the first  element of the third row is followed by the first element of the third Column.
      second  element of the third row  ...              second element of the third Col
      third   element of the third row  ...              third  element of the third C..

so the first  element of the fourth row is followed by the first element of the fourth Column.
      second  element of the fourth row  ...              second element of the fourth Col
      third   element of the fourth row  ...              third  element of the fourth C..

so the first  element of the fifth row is followed by the first element of the fifth Column.
      second  element of the fifth row  ...              second element of the fifth Col
      third   element of the fifth row  ...              third  element of the fifth C..

Any Idea is welcome and aprecciated. Please consider:

  • 6x6 is exemplary dataframes mitght differ be 4x4 or bigger than 6x6
  • 8x4 is might also happen

UPDATE: Okay maybe its possible to use df.T (transpose) Dataframe upper right ( abc..hi) and go by a loop which puts one column of df (lower lfet) and then one column of transposed upper right dataframe. As i have to leave for work now I'll give it a try tomorrow and update my Post again

1 Answers

based on what i understand, you can use the shape of the df and grab the left bottom and right upper matrix and concat them:

a,b = df.shape
m = int(a/2)
x = pd.DataFrame(df.iloc[:m,np.r_[m:b]].to_numpy()).T
y = pd.DataFrame(df.iloc[m:,:m].to_numpy())

out = (pd.concat((y,x),axis=1).sort_index(axis=1)
         .set_axis(df.columns,axis=1,inplace=False))

print(out)

     1  2    3  4    5  6
0  1.0  a  2.0  d  3.0  g
1  4.0  b  5.0  e  6.0  h
2  7.0  c  8.0  f  9.0  i
Related