StackSuperLow
StackSuperLow

Reputation: 39

Pandas: Remove rows with zero value in a DataFrame

enter image description here

(picture is a snapshot of my df)

I want to remove the rows that have a zero value. I don't want to modify the DataFrame, but create an assignment which reflects the DataFrame with no zero values in the 'amount spent' column.

Upvotes: 0

Views: 2836

Answers (1)

s3dev
s3dev

Reputation: 9701

This syntax can be used to view (index) a DataFrame based on a given condition:

# View whole DataFrame where `amount_spent` is not zero.
df[df['amount_spent'] != 0]

Here is the official pandas documentation on indexing.

What's happening? The df['amount_spent'] != 0 statement returns a 'mask' as a boolean array (Series), which is then passed into the 'rows parameter index' (if you will) of the overall DataFrame as: df[<masked_array>].

This will create a 'view' of the DataFrame and not alter it in any way.

Upvotes: 1

Related Questions