簡體   English   中英

熊貓:僅將數據框中的數字轉換為數字,保留其他所有內容

[英]Pandas: Convert only numbers in dataframe to numeric, keep everything else

源數據框

df1 = pd.DataFrame({'x': ['a', '2.0', '3.0'], 'y': ['4.0', 'b', '6.0']})

    x   y
0   a   4.0
1   2.0 b
2   3.0 6.0

第一次嘗試(使用“強制”)

如果我使用“強制”來處理字符串,則它們將被NaN取代

df2 = df1.apply(lambda x: pd.to_numeric(x.astype(str).str.replace(',',''), errors='coerce'))

    x   y
0   NaN 4.0
1   2.0 NaN
2   3.0 6.0

第二次嘗試(使用“忽略”)

如果我使用'ignore'處理字符串,則整個列都不會轉換(數字仍保留為文本字符串)

df2 = df1.apply(lambda x: pd.to_numeric(x.astype(str).str.replace(',',''), errors='ignore'))

    x   y
0   a   4.0
1   2.0 b
2   3.0 6.0

這是預期的輸出,因為如果選中to_numeric您將看到:

錯誤:{'ignore','raise','coerce'},默認為'raise'

如果為“ raise”,則無效的解析將引發異常
如果為“強制”,則將無效解析設置為NaN
如果為“ ignore”,則無效的解析將返回輸入

可能的解決方案是用原始值替換缺少的值-但將數字與字符串值混合在一起,例如注釋中指向@ anky_91:

df2 = df1.apply(lambda x: pd.to_numeric(x.astype(str).str.replace(',',''), errors='coerce'))

df3 = df2.fillna(df1)

要么:

df3 = df2.combine_first(df1)

檢查類型:

print (df3.applymap(type))
                 x                y
0    <class 'str'>  <class 'float'>
1  <class 'float'>    <class 'str'>
2  <class 'float'>  <class 'float'>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM