Pandas Need to Convert 0.0 Float to Empty String Without Messing Up Other Numbers in Pandas
Clash Royale CLAN TAG#URR8PPP
Pandas Need to Convert 0.0 Float to Empty String Without Messing Up Other Numbers in Pandas
I am pulling data from an API and doing calculations and transformations using Pandas.
These calculations create floats that I have to the second decimal place. 0.03, 0.04, 0.0 etc.
I then store this data into BigQuery and visualize in Google Data Studio(GDS). The problem is data studio cannot handle division with 0 numbers. So I need to remove the 0.0 from my series. The way I would think to do it is convert to a string, remove 0.0 and make it empty something like .str.replace('0.0', '')
But when I remove 0.0 I also remove the lead for all of the other decimals. When I do .round(decimals=3) to the series the 0.0 just stays as 0.0 so I cannot remove 0.00.
Any thoughts on how I can take that series of numbers and convert any 0.0's to empty?
Example
#In my dataframe I have something like Quantities
df = pd.DataFrame('Store': ['X', 'Y', 'Z', 'A', 'B'],
'Quantities': ['0.0', '0.034', '0.402', '1.0', '0.0'])
#I want to remove 0.0 and make it blank, but keep 0.034 etc
df = pd.DataFrame('Store': ['X', 'Y', 'Z'],
'Quantities': ['', '0.034', '0.402', '1.0', ''])
df.loc[df.calc.eq(0)] = # do something
Or if you want to drop rows with zeros:
df.mask(df.calc.eq(0)).dropna()
– user3483203
Aug 7 at 20:00
df.mask(df.calc.eq(0)).dropna()
I definitely don't want to drop, I added an example to my question.
– Jeff
Aug 7 at 20:29
try
df.mask(df.eq('0.0')).fillna('')
– user3483203
Aug 7 at 20:38
df.mask(df.eq('0.0')).fillna('')
Didn't do anything. Kept the 0.0
– Jeff
Aug 7 at 20:43
1 Answer
1
Use mask
:
mask
df = pd.DataFrame('Store': ['X', 'Y', 'Z', 'A', 'B'],
'Quantities': ['0.0', '0.034', '0.402', '1.0', '0.0'])
df['Quantities'] = df['Quantities'].mask(df['Quantities']=='0.0', '')
print(df)
Output:
Store Quantities
0 X
1 Y 0.034
2 Z 0.402
3 A 1.0
4 B
That was exactly what I needed! Thank you so much.
– Jeff
Aug 7 at 21:14
@Jeff You're welcome. Happy coding!
– Scott Boston
Aug 7 at 21:15
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Can you post a sample dataframe and desierd output? I think you need something like
df.loc[df.calc.eq(0)] = # do something
– user3483203
Aug 7 at 19:56