user18147555
user18147555

Reputation:

Build a data frame that each rows has incremental numbers in python

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

Upvotes: 0

Views: 215

Answers (4)

mozway
mozway

Reputation: 261860

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

Upvotes: 1

BENY
BENY

Reputation: 323326

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

Upvotes: 0

Riccardo Bucco
Riccardo Bucco

Reputation: 15374

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

Upvotes: 0

user7864386
user7864386

Reputation:

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

Upvotes: 0

Related Questions