python - 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
干杯
解决方案
您可以将非数值替换为缺失值:
df['col1'] = pd.to_numeric(df['col1'], errors='coerce').round(places)*100
推荐阅读
- python - 根据 df1 上的条件创建 pd 系列,并从 df2 或 df3 报告值
- excel - 如何用 VBa 选择字符串的最后一部分?
- python - Best practices, time-wise, for Reading and Writing files in python 3.7
- c# - 在运行时加载带有来自子文件夹的引用的程序集
- json - Laravel 6.2 : $request->all() return a empty array
- php - Why does the following SELECT statement not run?
- error-handling - 我应该在日志或内部异常中打印错误消息还是两者兼而有之?
- php - 登录问题我可以使用任何用户名和密码登录
- flutter - FIrestore Query Document in Collection Using Single Field/Attribute in Flutter
- java - 如何创建或增强使用 mapstruct 的自定义注释