如果您不需要对向下转型或错误处理进行特定控制,则一种快速且简单的方法是使用df = df.astype(float)
.
如需更多控制,您可以使用pd.DataFrame.select_dtypes https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html按 dtype 选择列。然后使用pd.to_numeric https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html在列的子集上。
Setup
df = pd.DataFrame([['656', 341.341, 4535],
['545', 4325.132, 562]],
columns=['col1', 'col2', 'col3'])
print(df.dtypes)
col1 object
col2 float64
col3 int64
dtype: object
Solution
cols = df.select_dtypes(exclude=['float']).columns
df[cols] = df[cols].apply(pd.to_numeric, downcast='float', errors='coerce')
Result
print(df.dtypes)
col1 float32
col2 float64
col3 float32
dtype: object
print(df)
col1 col2 col3
0 656.0 341.341 4535.0
1 545.0 4325.132 562.0