Home > Back-end >  How can I fill my dataframe with zeros n time s?
How can I fill my dataframe with zeros n time s?

Time:03-31

I have this dataframe :

index  B  C  D
0      8  7  9
1      6  2  7
2      7  6  9

I would like to have this output:

index  B  C  D
0      8  7  9
1      6  2  7
2      7  6  9
...     ....
n-1    0  0  0
n      0  0  0
      

I tried but couldn't do it. Thanks !!

CodePudding user response:

If need add new rows filled by 0 values use concat with DataFrame constructor:

N = 5
df = pd.concat(
    [df, pd.DataFrame(0, index=range(N), columns=df.columns)], 
    ignore_index=True
)

Or if there is default index use DataFrame.reindex:

N = 5
df = df.reindex(np.arange(df.index.max()   N   1), fill_value=0)

>>> print(df)
   B  C  D
0  8  7  9
1  6  2  7
2  7  6  9
3  0  0  0
4  0  0  0
5  0  0  0
6  0  0  0
7  0  0  0

CodePudding user response:

this is the first answer that came to my mind, I hope it helps.

import pandas as pd

df = pd.DataFrame({'B': [8, 7, 9],
                   'C': [6, 2, 7],
                   'D': [7, 6, 9]})

zeros = pd.DataFrame({'B': [0],
                   'C': [0],
                   'D': [0]})

n = 10
for row in range(n):
    df = pd.concat([df, zeros], axis=0)
    df.reset_index(drop=True, inplace=True)

CodePudding user response:

Given a Pandas DataFrame df you can expand it with N rows of 0. It seems best to use the numpy library.

import numpy as np
import pandas as pd

df = pd.DataFrame({"B": [8, 6, 7], "C": [7, 2, 6], "D": [9, 7, 9]})


def df_add_zero_rows(df: pd.DataFrame, N: int) -> pd.DataFrame:
    """Adds N rows of 0 to any DataFrame

    :param df: DataFrame where 0-rows will be added
    :param N: No. 0-rows to add.

    :return: The given DataFrame with appended N 0-rows.
    """
    zero_rows = pd.DataFrame(np.zeros((N, df.shape[0])), columns=df.columns)
    return pd.concat([df, zero_rows], ignore_index=True)

Using the function

>>> print(df_add_zero_rows(df, 5))

     B    C    D
0  8.0  7.0  9.0
1  6.0  2.0  7.0
2  7.0  6.0  9.0
3  0.0  0.0  0.0
4  0.0  0.0  0.0
5  0.0  0.0  0.0
6  0.0  0.0  0.0
7  0.0  0.0  0.0

CodePudding user response:

Try to create a zeros matrix with numpy

import numpy as np
import pandas as pd
d = pd.DataFrame(np.zeros((N_rows, N_cols)))

and use pd.concat() to merge the dataframes

df = pd.concat([df, d], ignore_index=True)
  • Related