Home > OS >  How to repeat row n times inside a iterrows
How to repeat row n times inside a iterrows

Time:12-21

For each row of a dataframe I want to repeat the row n times inside a iterrows in a new dataframe. Basically I'm doing this:

   df = pd.DataFrame(
    [
        ("abcd", "abcd", "abcd")  # create your data here, be consistent in the types.
    ],
    ["A", "B", "C"]  # add your column names here
)

n_times = 2
for index, row in df.iterrows():
    new_df = row.loc[row.index.repeat(n_times)]
new_df

and I get the following output:

0    abcd
0    abcd
1    abcd
1    abcd
2    abcd
2    abcd
Name: C, dtype: object

while it should be:

      A     B     C  
0    abcd  abcd  abcd
1    abcd  abcd  abcd

How should I proceed to get the desired output?

CodePudding user response:

The df.T attribute in Pandas is used to transpose a DataFrame. Transposing a DataFrame means to flip its rows and columns, so that the rows become columns and the columns become rows.

enter image description here

CodePudding user response:

I don't think you defined your df the right way.

df = pd.DataFrame(data = [["abcd", "abcd", "abcd"]],
                  columns = ["A", "B", "C"])

n_times = 2
for _ in range(n_times): 
    new_df = pd.concat([df, df], axis=0)

Is that how it should look like?

Is that how it should look like?

  • Related