首页 > 解决方案 > Pandas 乘以除 Div/0 以外的列

问题描述

我有以下数据框:

 In: df['col1']
 Out[228]: 
 0      -0.1
 1      -0.2
 2      -0.1
 3     #DIV/0

 Name: col1, dtype: object

我想将所有值乘以 100,将值设置为浮点数并四舍五入到小数点后 3 位。我可以这样做: df[col.name]=col.astype(float).round(places)*100 但是,由于 Div/0 值,此代码崩溃。

有人可以帮助创建一个执行以下规则但排除所有 Div/0 或 nan 值的函数:

 df[col.name]=col.astype(float).round(places)*100

干杯

标签: pythonpandas

解决方案


您可以将非数值替换为缺失值:

df['col1'] = pd.to_numeric(df['col1'], errors='coerce').round(places)*100

推荐阅读