Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Build a dataframe based on one repetetive row

I have a row and I want to build a dataframe based on this row. For example, I have a row with 5 value. I want to build a df with 4 rows and 5 column. here is the
desired output for me:

df = pd.DataFrame()
df['a']=[1]
df['b']=[2]
df['c']=[3]
df['d']=[1]
df['e']=[2]

Output:

      a     b     c     d     e
0     1     2     3     1     2
1     1     2     3     1     2
2     1     2     3     1     2
3     1     2     3     1     2

Can you help me iwth that? Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can repeat the index:

out = (df.loc[df.index.repeat(4)]
         .reset_index(drop=True)
      )

Output:

   a  b  c  d  e
0  1  2  3  1  2
1  1  2  3  1  2
2  1  2  3  1  2
3  1  2  3  1  2

Used input:

d = {'a': [1], 'b': [2], 'c': [3], 'd': [1], 'e': [2]}
df = pd.DataFrame(d)

rows and columns

Using repeat:

df.loc[df.index.repeat(4), df.columns.repeat(2)].reset_index(drop=True)

Output:

   a  a  b  b  c  c  d  d  e  e
0  1  1  2  2  3  3  1  1  2  2
1  1  1  2  2  3  3  1  1  2  2
2  1  1  2  2  3  3  1  1  2  2
3  1  1  2  2  3  3  1  1  2  2

Using numpy.tile for a different order:

import numpy as np
df.loc[df.index.repeat(4), np.tile(df.columns, 2)].reset_index(drop=True)

Output:

   a  b  c  d  e  a  b  c  d  e
0  1  2  3  1  2  1  2  3  1  2
1  1  2  3  1  2  1  2  3  1  2
2  1  2  3  1  2  1  2  3  1  2
3  1  2  3  1  2  1  2  3  1  2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading