7

I made the following code that takes out all of the zero's from my df. However when there is a number containing a zero it takes them out as well.

e.g.
3016.2     316.2
   0.235      .235


data_usage_df['Data Volume (MB)'] = data_usage_df['Data Volume (MB)'].str.replace('0', '')

Could you help me to figure out how I do an exact match of the cell that equals 0 and replace it with a blank value.

2 Answers 2

9
data_usage_df = data_usage_df.astype(str)
data_usage_df['Data Volume (MB)'].replace(['0', '0.0'], '', inplace=True)
Sign up to request clarification or add additional context in comments.

1 Comment

Simplest and cleanest solution I've found. For anyone not using str remove the quotes from around the 0 and 0.0.
3

I think you need add ^ for matching start of string and $ for end of string:

data_usage_df['Data Volume (MB)']=data_usage_df['Data Volume (MB)'].str.replace('^0.0$', '')

Sample:

data_usage_df = pd.DataFrame({'Data Volume (MB)':[3016.2, 0.235, 1.4001, 0, 4.00]})

print (data_usage_df)
runfile('C:/Dropbox/work-joy/so/_t/test.py', wdir='C:/Dropbox/work-joy/so/_t')
   Data Volume (MB)
0         3016.2000
1            0.2350
2            1.4001
3            0.0000
4            4.0000

data_usage_df['Data Volume (MB)'] = data_usage_df['Data Volume (MB)'].astype(str)
data_usage_df['Data Volume (MB)']=data_usage_df['Data Volume (MB)'].str.replace('^0.0$', '')

print (data_usage_df)
  Data Volume (MB)
0           3016.2
1            0.235
2           1.4001
3                 
4              4.0

Another solution is converting column to_numeric and where is 0 give empty space:

data_usage_df['Data Volume (MB)'] = data_usage_df['Data Volume (MB)'].astype(str)

data_usage_df.ix[pd.to_numeric(data_usage_df['Data Volume (MB)'], errors='coerce') == 0, 
                                                              ['Data Volume (MB)']] = ''

print (data_usage_df)
  Data Volume (MB)
0           3016.2
1            0.235
2           1.4001
3                 
4              4.0

1 Comment

Great thanks for your help! I will accept the answer as soon as I can accept it, all the best

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.