5

I want to append a specific amount of empty rows to that df

df = pd.DataFrame({'cow': [2, 4, 8],
                  'shark': [2, 0, 0],
                  'pudle': [10, 2, 1]})

with df = df.append(pd.Series(), ignore_index = True) I append one empty row, how can I append x amount of rows ?

5 Answers 5

9

You can use df.reindex to achieve this goal.

df.reindex(list(range(0, 10))).reset_index(drop=True)

   cow  shark  pudle
0  2.0    2.0   10.0
1  4.0    0.0    2.0
2  8.0    0.0    1.0
3  NaN    NaN    NaN
4  NaN    NaN    NaN
5  NaN    NaN    NaN
6  NaN    NaN    NaN
7  NaN    NaN    NaN
8  NaN    NaN    NaN
9  NaN    NaN    NaN

The arguments you provide to df.reindex is going to be the total number of rows the new DataFrame has. So if your DataFrame has 3 objects, providing a list that caps out at 10 will add 7 new rows.

Sign up to request clarification or add additional context in comments.

3 Comments

This converts int64 columns to float64, which is undesirable.
@JoshuaChia it worked for OP hence it was marked as resolved so your comment is not exactly truthful.
desirable enough for OP but not desireable enough in general, to be truthful, though OP's original answer appending one row has the same problem.
2

I'm not too pandas savvy, but if you can already add one empty row, why not just try writing a for loop and appending x times?

for i in range(x):
    df = df.append(pd.Series(), ignore_index = True)

Comments

1

You could do:

import pandas as pd

df = pd.DataFrame({'cow': [2, 4, 8],
                  'shark': [2, 0, 0],
                  'pudle': [10, 2, 1]})

n = 10
df = df.append([[] for _ in range(n)], ignore_index=True)
print(df)

Output

    cow  shark  pudle
0   2.0    2.0   10.0
1   4.0    0.0    2.0
2   8.0    0.0    1.0
3   NaN    NaN    NaN
4   NaN    NaN    NaN
5   NaN    NaN    NaN
6   NaN    NaN    NaN
7   NaN    NaN    NaN
8   NaN    NaN    NaN
9   NaN    NaN    NaN
10  NaN    NaN    NaN
11  NaN    NaN    NaN
12  NaN    NaN    NaN

Comments

1

Try with reindex

out = df.reindex(df.index.tolist()+[df.index.max()+1]*5)#reset_index(drop=True)
Out[93]: 
   cow  shark  pudle
0  2.0    2.0   10.0
1  4.0    0.0    2.0
2  8.0    0.0    1.0
3  NaN    NaN    NaN
3  NaN    NaN    NaN
3  NaN    NaN    NaN
3  NaN    NaN    NaN
3  NaN    NaN    NaN

1 Comment

index is a little borked, might want to throw a reset_index in there
0

Create an empty dataframe of the appropriate size and append it:

import numpy as np
df = df.append(pd.DataFrame([[np.nan] * df.shape[1]] * n,columns=df.columns), 
               ignore_index = True)

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.