Python Pandas - Update value if condition in 3 columns are met

To update a value in dataframe if 3 certain values are met, we can hard code for the three particular conditions. By Pranit Sharma Last updated : September 26, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Updating value if condition in 3 columns are met

If all these conditions are satisfied, we can update the value. For this purpose, we will use the pandas.DataFrame.loc property which is used whenever we want to filter some rows.

The pandas.DataFrame.loc property is an effective and efficient way of selecting rows or columns. Also, this method requires some kind of condition as a parameter based on which it filters out the data from the DataFrame.

The pandas.DataFrame.loc property is a type of data selection method which takes the name of a row or column as a parameter. To perform various operations using the The pandas.DataFrame.loc property, we need to pass the required condition of rows and columns to get the filtered data.

Let us understand with the help of an example,

Python program to update value if condition in 3 columns are met

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'Fruits':['Banana','Apple','pomegranate'],
    'Vegetables':['Potato','Soya','BottleGuard'],
    'Diet_complete':["Yes",np.nan,np.nan]
}

# Creating DataFrame
df = pd.DataFrame(d)

# Display Original DataFrames
print("Created DataFrame: 2\n",df,"\n")

# Updating values
df.loc[(df['Fruits'] == 'Apple') & (df['Vegetables'] == 'Soya'),'D'] = 'Yes'

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output

The output of the above program is:

Example: Update value if condition in 3 columns are met

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.