Rookie
Rookie

Reputation: 37

Pandas : Converting Dataframe upper triangular to lower and vice versa

I am adding a new function which converts the DataFrame to lower triangle if its an upper triangle and vice versa. The data I am using always has first two rows filled with the first index only.

I tried using the solution from this problem Pandas: convert upper triangular dataframe by shifting rows to the left

 Data : 
      0         1         2      3  
0  1.000000  NaN       NaN      NaN
1  0.421655  NaN       NaN      NaN 
2  0.747064  5.000000  NaN      NaN
3  0.357616  0.631622  8.000000 NaN

which should be turned into:

 Data : 
      0         1         2         3        
0  NaN       8.000000  0.631622  0.357616
1  NaN       NaN       5.000000  0.747064
2  NaN       NaN       NaN       0.421655
3  NaN       NaN       NaN       1.000000

Upvotes: 2

Views: 1797

Answers (2)

Andy L.
Andy L.

Reputation: 25239

your system should be having numpy installed. So, using numpy.flip is another way and provide more readable options

In [722]: df
Out[722]:
          0         1    2   3
0  1.000000       NaN  NaN NaN
1  0.421655       NaN  NaN NaN
2  0.747064  5.000000  NaN NaN
3  0.357616  0.631622  8.0 NaN    

In [724]: import numpy as np
In [725]: df_flip = pd.DataFrame(np.flip(df.values))

In [726]: df_flip
Out[726]:
    0    1         2         3
0 NaN  8.0  0.631622  0.357616
1 NaN  NaN  5.000000  0.747064
2 NaN  NaN       NaN  0.421655
3 NaN  NaN       NaN  1.000000

Upvotes: 0

BENY
BENY

Reputation: 323246

Just like you need reverse order for row and columns

yourdf=df.iloc[::-1,::-1]
yourdf
Out[94]: 
    3    2         1         0
3 NaN  8.0  0.631622  0.357616
2 NaN  NaN  5.000000  0.747064
1 NaN  NaN       NaN  0.421655
0 NaN  NaN       NaN  1.000000

Upvotes: 6

Related Questions