在凌乱的 pandas 数据框中转换数据类型?

Converting dtypes in messy pandas data-frame?

我有一个大数据框。我想将它们转换为适当的数据类型。问题是在几个数字列中有字符串。我知道 convert_dtypes 和 to_numeric。前者的问题在于,一旦那里有字符串,它就不会将列推断为 int/float,另一方面,to_numeric 具有将所有无效示例转换为 nan 的“强制”。 to_numeric 的问题是有几个列是字符串,所以我不能只 运行 它在所有列上。

所以我正在寻找一个将数据类型转换为数字的函数,如果其中有一定百分比的数值。如果能设置一个门槛就好了

如前所述,数据集很大,所以我更喜欢一些自动处理所有列的解决方案。

使用自定义函数将列转换为数字,如果匹配条件 return 数字列,否则 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