Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn zero values to empty cells in Pandas

Tags:

python

pandas

I have a "single-liner" dataframe like this:

         Value 1   Value 2   Value 3
code
123            0         3       231

I want to turn the zero values into empty, so it gets to look like this:

         Value 1   Value 2   Value 3
code
123                      3       231

How could I do that?

like image 531
aabujamra Avatar asked Feb 23 '18 21:02

aabujamra


People also ask

What is a correct method to fill empty cells with a new value in pandas?

In this method, we will use “df. fillna(method='ffill')” , which is used to propagate non-null values forward or backward.

How do you replace zeros in pandas?

You can also use df. replace(np. nan,0) to replace all NaN values with zero. This replaces all columns of DataFrame with zero for Nan values.


2 Answers

You can use pandas.DataFrame.eq to find the location of all the zero values across the entire DataFrame, and then replace this with something else, maybe np.nan.

import numpy as np
df[df.eq(0)] = np.nan

Though if you have only one row, you can also replace it with an empty string since you (probably) don't have to worry about the dtype for the column changing:

df[df.eq(0)] = ''
like image 117
pault Avatar answered Oct 27 '22 21:10

pault


The code below reads like so: set the column 'Value 1' equal to nothing where column 'Value 1' is equal to 0.

df.loc[df['Value 1'] == 0, 'Value 1'] = ''
like image 27
Brian Avatar answered Oct 27 '22 21:10

Brian