Dropping a row in pandas DataFrame if any value in row becomes 0

Given a Pandas DataFrame, we have to drop a row if any value in row becomes 0.
Submitted by Pranit Sharma, on June 24, 2022

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

Rows in pandas are the different cell (column) values that are aligned horizontally and also provide uniformity. Each row can have the same or different value. Rows are generally marked with the index number but in pandas, we can also assign index names according to the needs. In pandas, we can create, read, update and delete a column or row value.

To drop a row if a value becomes 0 in that row, for this purpose, we will use the ~ invert operator which is used as a not operator and we will select only those values which are not 0 from that row.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

Python code to drop a row in pandas DataFrame if any value in row becomes 0

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'One':[1,0,2],
    'Two':[1,2,3],
    'Three':[0,1,2],
    'Four':[4,5,6]
}

# Creating  dataframe
df = pd.DataFrame(d)

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

# Removing a row if any value becomes 0
df = df[~(df == 0).any(axis=1)]

# Display result
print("DataFrame after dropping rows\n",df)

Output:

Example: Dropping a row in pandas DataFrame

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT


What's New (MCQs)



Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.