Sator
Sator

Reputation: 776

append specific amount of empty rows to pandas dataframe

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 ?

Upvotes: 5

Views: 8943

Answers (5)

BENY
BENY

Reputation: 323376

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

Upvotes: 1

Dani Mesejo
Dani Mesejo

Reputation: 61930

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

Upvotes: 1

gold_cy
gold_cy

Reputation: 14236

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.

Upvotes: 9

DYZ
DYZ

Reputation: 57105

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)

Upvotes: 0

Luke Lewis
Luke Lewis

Reputation: 110

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)

Upvotes: 2

Related Questions