the man
the man

Reputation: 1391

Rounding all numbers in a dataframe containing numbers and strings?

I have a dataframe which contains floats and also strings. I want to round all of the floats to one decimal place.

An example df is depicted below;

Y     1      2      3
X
1    5.19   "a"    "a"
2    6.68   6.22   "b"
3    "b"    8.23   8.55

Now, I want to round all of the floats by 1 decimal place. My actual dataframe is a lot larger than this, but the strings arr only "a" or "b".

I've tried doing df[(df != "a") & (df != "b")] = df.round(1) but this doesn't change anything?

Upvotes: 0

Views: 590

Answers (1)

anky
anky

Reputation: 75080

Try with pd.to_numeric

df.apply(pd.to_numeric,errors='coerce').round(1).fillna(df)

Or:

s = df.stack()
pd.to_numeric(s,errors='coerce').round(1).fillna(s).unstack()

Y    1    2    3
X               
1  5.2  "a"  "a"
2  6.7  6.2  "b"
3  "b"  8.2  8.6

EDIT per comments:

s = df.stack()
s1 = pd.to_numeric(s,errors='coerce').round(1)
s1.astype(str).add('%').mask(s1.isna(),s).unstack()

Y     1     2     3
X                  
1  5.2%   "a"   "a"
2  6.7%  6.2%   "b"
3   "b"  8.2%  8.6%

Upvotes: 4

Related Questions