Reputation: 125
I have a dataframe : df = pd.DataFrame([["abcd", 1.9923], [2.567345454, 5]])
I want to round it up to 2 decimal places for all the floats. I am using: df.round(decimals=2)
However, I am observing that it is working only if the entire dataframe is either float
or int
. Presence of any single string in the dataframe is not doing any changes to the entire dataframe. Any help is highly appreciated.
Upvotes: 2
Views: 1242
Reputation: 862741
If there are mixed numeric with strings values is possible use custom lambda function:
#first column is filled by strings, so 1. solution not working
df = df.applymap(lambda x: round(x, 2) if isinstance(x, (float, int)) else x)
print (df)
0 1
0 abcd 1.99
1 2.57 5.00
If need convert to numeric and round:
df = pd.DataFrame([["abcd", 1.9923], ["2.567345454", 5]])
def f(x):
try:
return round(float(x), 2)
except:
return x
df = df.applymap(f)
print (df)
0 1
0 abcd 1.99
1 2.57 5.00
Upvotes: 2