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

Time:02-20

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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
  • Related