[英]How to round only numbers in python dataframe columns with object mixed
我有一個名為“df”的 dataframe 作為圖片。 在這個 dataframe 中有“null”作為對象(dtype)和數字。 我希望僅舍入 (2) 多列中的數值。 我已經編寫了這段代碼,但不斷收到“TypeError: 'int' object is not iterable”作為 TypeError。 *第一行代碼是將 na 轉換為“null”,因為其他數字需要是數字數據類型。
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)
round(2) 多列中僅數值的最簡單代碼是什么?
round
之前fillna
:
df['skor_change_w_ts'] = (pd.to_numeric(df['skor_change_w_ts'], errors='coerce')
.round(2).fillna("null", downcast='infer')
)
輸入示例:
df = pd.DataFrame({'skor_change_w_ts': [1, 2.6666, 'null']})
Output:
skor_change_w_ts
0 1.0
1 2.67
2 null
您根本不需要 call.fillna() , coerce 會為您完成。
df['skor_change_w_ts'] = (pd.to_numeric(df['skor_change_w_ts'], errors='coerce').round(2)
應該做的伎倆。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.