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 | |
0 | 0.0 |
1 | 0.0 |
2 | 0.0 |
3 | 0.0 |
4 | 0.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 | |
0 | 1.0 |
1 | 1.0 |
2 | 1.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 | |
0 | NaN |
1 | NaN |
2 | NaN |
3 | NaN |
4 | NaN |
5 | NaN |