python - pandas multiindex DataFrame中的圆形浮点数
问题描述
我得到了一个用浮点数索引的 pandas multiindex DataFrame。考虑以下示例:
arrays = [[0.21,0.21,0.21,0.22,0.22,0.22,0.23,0.23,0.23],
[0.81,0.8200000000000001,0.83,0.81,0.8200000000000001,0.83,0.81,0.8200000000000001,0.83]]
df = pd.DataFrame(np.random.randn(9, 2), index=arrays)
df
# 0 1
# 0.21 0.81 -2.234036 -0.145643
# 0.82 0.367248 -1.471617
# 0.83 -0.764520 0.686241
# 0.22 0.81 1.380429 1.546513
# 0.82 1.230707 1.826980
# 0.83 -1.198403 0.377323
# 0.23 0.81 -0.418367 -0.125763
# 0.82 0.682860 -0.119080
# 0.83 -1.802418 0.357573
我以这种形式获得了这个 DataFrame。现在,如果我想检索条目,df.loc[(0.21, 0.82)]
我会收到一个错误,因为索引并没有真正携带0.82
but 0.8200000000000001
。我事先不知道这些问题出现在索引的什么地方。我该如何解决这个问题?我的想法是将多索引的两个级别四舍五入到有效的小数位数,在这种情况下为 2。但怎么可能呢?有更好的解决方案吗?
解决方案
您可以使用该rename
函数将函数应用于您的每个值MultiIndex
:
df = df.rename(index=lambda val: round(val, 2))
print(df.loc[(.21, .82)])
0 0.260015
1 -0.233822
Name: (0.21, 0.82), dtype: float64
但是,由于https://docs.python.org/3/tutorial/floatingpoint.html (简短示例),我不确定是否将浮点数作为特定键
>>> .1 + .1 + .1 == .3
False
虽然我很好奇其他人对此有何看法。因为我不确定您会遇到的现实问题。
您始终可以将浮点数截断为字符串,然后通过字符串访问数据框以确保准确性:
df = df.rename(index="{:.2f}".format)
print(df.loc[("0.21", "0.82")]) # note that the leading 0 is important here now
0 0.260015
1 -0.233822
Name: (0.21, 0.82), dtype: float64
推荐阅读
- python - 如何在不导入检查(或任何其他模块)的情况下在 Python 中获取函数的参数名称
- javascript - JavaScript 用图像替换文本
- identityserver4 - 验证 Google emailId 并重定向到错误页面
- android - Android 中的 UI 测试在 RecyclerView 滚动时发生错误
- android - 我可以使用后台任务每 1 秒处理一次来自服务器的数据吗?
- oauth - 为什么需要密码,为什么在 OAuth2.0 中不需要
- ios - 尝试使用 TOSMBClient 使用 SMB1 上传文件时的 EXC_BAD_ACCESS
- javascript - TypeError:无法将 undefined 或 null 转换为对象 React js 材料表
- sql - 在 Excel 中过滤和显示唯一的列对
- android - 在 Android 中从 uri 显示 PDF