我有一個大資料框。我想將它們轉換為適當的 dtype。問題是在幾個數字列中有字串。我知道 convert_dtypes 和 to_numeric。對于前者,問題在于它不會在存在字串時立即將列推斷為 int/float,另一方面 to_numeric 具有“強制”,將所有無效示例轉換為 nan。to_numeric 的問題是有幾列是字串,所以我不能只在所有列上運行它。
所以我正在尋找一個函式,如果其中有一定百分比的數字值,它可以將 dtypes 轉換為數字。如果可以為此設定閾值,那就太好了。
如前所述,資料集很大,所以我更喜歡一些自動處理所有列的解決方案。
uj5u.com熱心網友回復:
使用自定義函式將列轉換為數字,如果匹配條件回傳數字列,否則原始列在DataFrame.apply:
print (df)
a b c d e
0 1 5 4 3 8
1 7 8 9 f 9
2 c c g g 4
3 4 t r e 4
def f(x, thresh):
y = pd.to_numeric(x, errors='coerce')
return y if y.notna().mean() > thresh else x
thresh = 0.7
df1 = df.apply(f, args= (thresh,))
print (df1)
a b c d e
0 1.0 5 4 3 8
1 7.0 8 9 f 9
2 NaN c g g 4
3 4.0 t r e 4
print (df1.dtypes)
a float64
b object
c object
d object
e int64
dtype: object
帶有缺失值的修改解決方案(如果存在):
print (df)
a b c d e
0 1 5 4 3 8
1 7 8 NaN f 9
2 c c NaN g 4
3 4 t r e 4
def f(x, thresh):
y = pd.to_numeric(x, errors='coerce')
return y if (y.notna() | x.isna()).mean() > thresh else x
thresh = 0.7
df1 = df.apply(f, args= (thresh,))
print (df1)
a b c d e
0 1.0 5 4.0 3 8
1 7.0 8 NaN f 9
2 NaN c NaN g 4
3 4.0 t NaN e 4
print (df1.dtypes)
a float64
b object
c float64
d object
e int64
dtype: object
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/384390.html
上一篇:使用loc與僅使用方括號內的性能
