lassence.net

Field notes from the AI frontier

Create a DataFrame of zeros or nulls

--- archive: codebook, 2020–2023 · topic: Pandas ---

Sometimes, you just want to create a DataFrame with nothing interesting in it. It may be useful a few lines code later. These DataFrames can serve various purposes, from placeholders to specific mathematical operations.

DataFrame of zeros

Creating a DataFrame of zeros can be done using the NumPy zeros() function. This is useful when you need a placeholder DataFrame or want to initialize a DataFrame for iterative calculations.

# Import libraries
import pandas as pd
import numpy as np

# Create a DataFrame of zeros
pd.DataFrame(np.zeros(5), columns=['zeros'])
zeros
00.0
10.0
20.0
30.0
40.0

You can also create a Series of zeros using the same approach:

# It works with Series as well, obviously
pd.Series(np.zeros(5))
0    0.0
1    0.0
2    0.0
3    0.0
4    0.0
dtype: float64

DataFrame of ones

While you’re at it, you can as well create a DataFrame of ones, because numpy as it covered with ones():

# Create a Series of ones
pd.DataFrame(np.ones(3))
0
01.0
11.0
21.0

DataFrame of Null values

Creating a DataFrame of NaN values can be done using NumPy's nan object. This can be useful when you need to represent missing or undefined data.

# Create a DataFrame of NaN
pd.DataFrame([np.nan]*6)
0
0NaN
1NaN
2NaN
3NaN
4NaN
5NaN