Home > other >  python: repeated expansion of dataframe
python: repeated expansion of dataframe

Time:09-30

My dataframe is:

X=[0,1,2
   1,0,3
   2,3,0]

X shape is 3*3. For every value, I want to expand n times in every row and column, that is, transform my dataframe to the shape of (3*n)*(3*n), if n=2, my ideal result is:

X=[0,0,1,1,2,2
   0,0,1,1,2,2
   1,1,0,0,3,3
   1,1,0,0,3,3
   2,2,3,3,0,0
   2,2,3,3,0,0]

How to do that? thanks!

CodePudding user response:

You could use numpy.repeat, as follows:

import numpy as np

X = np.array([[0, 1, 2],
              [1, 0, 3],
              [2, 3, 0]] )
res = X.repeat(2, axis=1).repeat(2, axis=0)
print(res)

Output

[[0 0 1 1 2 2]
 [0 0 1 1 2 2]
 [1 1 0 0 3 3]
 [1 1 0 0 3 3]
 [2 2 3 3 0 0]
 [2 2 3 3 0 0]]

CodePudding user response:

A base python solution (without imports) would be a nested list comprehension:

>>> [[y for y in x for _ in range(3)] for x in X for _ in range(3)]
[[0, 0, 0, 1, 1, 1, 2, 2, 2],
 [0, 0, 0, 1, 1, 1, 2, 2, 2],
 [0, 0, 0, 1, 1, 1, 2, 2, 2],
 [1, 1, 1, 0, 0, 0, 3, 3, 3],
 [1, 1, 1, 0, 0, 0, 3, 3, 3],
 [1, 1, 1, 0, 0, 0, 3, 3, 3],
 [2, 2, 2, 3, 3, 3, 0, 0, 0],
 [2, 2, 2, 3, 3, 3, 0, 0, 0],
 [2, 2, 2, 3, 3, 3, 0, 0, 0]]
>>> 

CodePudding user response:

One way using pandas.Index.repeat:

ind = df.index.repeat(2)
new_df = df.iloc[ind, ind]
print(new_df)

Output:

   0  0  1  1  2  2
0  0  0  1  1  2  2
0  0  0  1  1  2  2
1  1  1  0  0  3  3
1  1  1  0  0  3  3
2  2  2  3  3  0  0
2  2  2  3  3  0  0
  • Related