简体   繁体   中英

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

在此处输入图像描述

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM