YJP
YJP

Reputation: 67

How to round only numbers in python dataframe columns with object mixed

enter image description here

I have a dataframe named "df" as the picture. In this dataframe there are "null" as object(dtype) and numerics. I wish to round(2) only the numeric values in multiple columns. I have written this code but keep getting "TypeError: 'int' object is not iterable" as TypeError. *The first line code is to convert na's to "null", since other numbers need to be numeric dtype.

df['skor_change_w_ts']=pd.to_numeric(df['skor_change_w_ts'], errors='coerce').fillna("null", downcast='infer')

for i in len(df):
    if df['skor_change_w_ts'][i] is float:
        df['skor_change_w_ts'][i]=df['skor_change_w_ts'][i].round(2)

What would be the most simple code to round(2) only numeric values in multiple columns?

Upvotes: 0

Views: 834

Answers (2)

big_water_guy
big_water_guy

Reputation: 31

You don't need to call .fillna() at all, coerce will do that for you.

df['skor_change_w_ts'] = (pd.to_numeric(df['skor_change_w_ts'], errors='coerce').round(2) 

Should do the trick.

Upvotes: 1

mozway
mozway

Reputation: 260745

round before fillna:

df['skor_change_w_ts'] = (pd.to_numeric(df['skor_change_w_ts'], errors='coerce')
                             .round(2).fillna("null", downcast='infer')
                          )

Example input:

df = pd.DataFrame({'skor_change_w_ts': [1, 2.6666, 'null']})

Output:

  skor_change_w_ts
0              1.0
1             2.67
2             null

Upvotes: 1

Related Questions