0

I want to build a data frame with m column and n rows. Each rows start with 1 and increment by 1 until m.

I've tried to find a solution, but I found only this solution for the columns. I have also added a figure of a simple case.

enter image description here

1
  • Please show what you have tried and how it's not doing what you want. Commented Feb 19, 2022 at 17:28

4 Answers 4

1

Using assign to broadcast the rows in an empty DataFrame:

df = (
 pd.DataFrame(index=range(3))
   .assign(**{f'c{i}': i+1 for i in range(4)})
    )

Output:

   c0  c1  c2  c3
0   1   2   3   4
1   1   2   3   4
2   1   2   3   4
Sign up to request clarification or add additional context in comments.

Comments

0

You can use np.tile:

import numpy as np
m = 4
n = 3
out = pd.DataFrame(np.tile(np.arange(1,m), (n,1)), columns=[f'c{num}' for num in range(m-1)])

Output:

   c0  c1  c2
0   1   2   3
1   1   2   3
2   1   2   3

1 Comment

Thank you. You are always helpful.
0

Try with this (no additional libraries needed):

df = pd.DataFrame({f'c{n}': [n + 1] * (m - 1) for n in range(m)})

Result with m = 4:

   c0  c1  c2  c3
0   1   2   3   4
1   1   2   3   4
2   1   2   3   4

Comments

0

We just do np.one

m = 3
n = 4
out = pd.DataFrame(np.ones((m,n))*(np.arange(n)+1))
Out[139]: 
     0    1    2    3
0  1.0  2.0  3.0  4.0
1  1.0  2.0  3.0  4.0
2  1.0  2.0  3.0  4.0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.