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

Time:11-30

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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related