Reputation: 4972
I have a dataframe containing fields having numbers with string and empty values like the in the following:
import pandas as pd
import numpy as np
df = pd.DataFrame()
new_row = [{'Col1': 1.0, 'Col2': 'c', 'Col3': 1.02}, {'Col1': 1.0, 'Col2': 'e', 'Col3': ''}]
df = df.append(new_row, ignore_index=True)
The dataframe:
Col1 Col2 Col3
1.0 c 2.0
1.0 e
I need to remove .0
from fields having strings as well, so the dataframe should look like this:
Col1 Col2 Col3
1.0 c 2
1.0 e
It is not only for col3
because I have a huge real life dataframe. I tried the following:
for col in df.columns:
print(col)
df[col] = df[col].apply(lambda x: f'{x: .0f}')
And it returned an error:
ValueError: Unknown format code 'f' for object of type 'str'
So how can I remove the floating point from numbers included within a field having string values?
Upvotes: 0
Views: 470
Reputation: 862641
If need replace .0
only for columns with mixed values strings and numbers with .0
use:
#data was changed for match sample data with 2.0 in Col3
df = pd.DataFrame()
new_row = [{'Col1': 1.0, 'Col2': 'c', 'Col3': 2.0}, {'Col1': 1.0, 'Col2': 'e', 'Col3': ''}]
df = df.append(new_row, ignore_index=True)
c = df.select_dtypes(object).columns
df[c] = df[c].astype(str).replace('\.0$','', regex=True)
print (df)
Col1 Col2 Col3
0 1.0 c 2
1 1.0 e
If need processing all values:
def f(x):
try:
return f'{x: .0f}'
except:
return x
df = df.applymap(f)
print (df)
Col1 Col2 Col3
0 1 c 2
1 1 e
Solution with test floats like integers (end by .0
):
df = pd.DataFrame()
new_row = [{'Col1': 1.15, 'Col2': 'c', 'Col3': 2.0}, {'Col1': 1.064, 'Col2': 'e', 'Col3': ''}]
df = df.append(new_row, ignore_index=True)
def f(x):
try:
if x.is_integer():
return f'{x: .0f}'
else:
return x
except:
return x
df = df.applymap(f)
print (df)
Col1 Col2 Col3
0 1.150 c 2
1 1.064 e
Upvotes: 1
Reputation: 959
If you specifically want a string in your dataframe you cam use the try and ask for forgiveness pattern
def truncate(x):
try:
return '{0:1.0f}'.format(x)
except ValueError:
return x
Unfortunately I cannot test this directly on a dataframe.
Upvotes: 2
Reputation: 7666
Here is a simple solution
convert = lambda x: '%.0f' % x if isinstance(x,float) else x
df['Col3'] = df['Col3'].apply(convert)
Upvotes: 2