1

I have test the code to add multiple empty row to Pandas DataFrame it worked.

import pandas as pd

df = pd.DataFrame({'name': ["James", "White", "John"],
                   'rebounds': [7, 7, 8]})

for i in range(100):
    dft =  df.columns.values.tolist()
    s = pd.Series(dft)
    df.loc[len(df)] =s
print(len(df.index))

In my application I have this code, its adding 16 empty rows but it adds only 4 rows.

    print(f"Before adding {len(df3.index)}")
    dft =  df3.columns.values.tolist()
    s = pd.Series(dft)
    for i in range(16):
        df3.loc[len(df3)] =s

    print(f"After adding {len(df3.index)}")

Output

Before adding 221
After adding 225

why its not adding 16 empty rows in my application code? How to troubleshoot this issue?

Thanks

3
  • I'd recommend stepping through with a debugger. Then you'll be able to run the line in your for-loop one-at-a-time and compare against the dataframe and see what is being added when. Commented Oct 17, 2022 at 21:24
  • 1
    also, separate from the main question completely, but a common convention when you have a for-loop but you aren't using the thing you are looping over (like you have here where you don't use the i in the for i in range() is to instead do for _ in range(16). This can make it clearer to anyone reading the code that you are never going to use / never going to call the i (which we have changed to _). it won't have any change on how the code runs, just one how someone reads it Commented Oct 17, 2022 at 21:26
  • @scotscotmcc thanks, below answer helped me on this issue. Commented Oct 17, 2022 at 21:30

1 Answer 1

1

You might have duplicated indices. For example if you array has 221 rows but an indice 222, no row will be added.

A more robust method could be to concat:

N = 4
df = pd.concat([df, pd.DataFrame(columns=df.columns,
                                 index=range(len(df), len(df)+N))
                ])

output:

    name rebounds
0  James        7
1  White        7
2   John        8
3    NaN      NaN
4    NaN      NaN
5    NaN      NaN
6    NaN      NaN
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.