In Pandas, the null value is represented by the keyword “None”. It is used to represent the absence of the data in a column or row. In this tutorial, we’ll learn how to assign a null value in Python Pandas.
Steps:
1. Import pandas library
To work with Pandas, we need to import the Pandas library. We can use the following code to import pandas:
1 |
import pandas as pd |
2. Create a DataFrame
Now, let’s create a DataFrame with some data. We can use the following code to create a DataFrame:
1 |
data = {'Name': ['John', 'Paul', 'George', 'Ringo'], 'Age': [28, 22, 24, 26], 'City': ['London', 'New York', 'Los Angeles', 'Paris']} df = pd.DataFrame(data) |
This will create a DataFrame with three columns ‘Name’, ‘Age’, and ‘City’.
3. Assign the null value to a cell
To assign a null value to a cell, we can use the ‘None’ keyword. Let’s assign a null value to the ‘Age’ column of the second row:
1 |
df.loc[1, 'Age'] = None |
This will assign a null value to the ‘Age’ column of the second row.
4. Check for null values
To check if there are any null values in the DataFrame, we can use the isnull() function. Let’s check for null values in the ‘Age’ column:
1 |
df['Age'].isnull() |
This will return a boolean Series with ‘True’ values where there are null values and ‘False’ values where there are no null values.
5. Replace null values with a value
To replace null values with a value, we can use the fillna() function. Let’s replace the null value in the ‘Age’ column with 0:
1 |
df['Age'].fillna(0, inplace=True) |
This will replace the null value in the ‘Age’ column with 0.
Conclusion:
Assigning null value in Python Pandas is a simple task. We can use the ‘None’ keyword to assign null value to a cell and use the isnull() function to check for null values. We can also use the fillna() function to replace null values with a value.
Code:
1 2 3 4 5 6 7 8 9 10 |
import pandas as pd data = {'Name': ['John', 'Paul', 'George', 'Ringo'], 'Age': [28, 22, 24, 26], 'City': ['London', 'New York', 'Los Angeles', 'Paris']} df = pd.DataFrame(data) df.loc[1, 'Age'] = None print(df['Age'].isnull()) df['Age'].fillna(0, inplace=True) print(df) |
Output:
{'Name': {0: 'John', 1: 'Paul', 2: 'George', 3: 'Ringo'}, 'Age': {0: 28.0, 1: nan, 2: 24.0, 3: 26.0}, 'City': {0: 'London', 1: 'New York', 2: 'Los Angeles', 3: 'Paris'}} 0 False 1 True 2 False 3 False Name: Age, dtype: bool Name Age City 0 John 28 London 1 Paul 0 New York 2 George 24 Los Angeles 3 Ringo 26 Paris