首页 > 解决方案 > 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.82but 0.8200000000000001。我事先不知道这些问题出现在索引的什么地方。我该如何解决这个问题?我的想法是将多索引的两个级别四舍五入到有效的小数位数,在这种情况下为 2。但怎么可能呢?有更好的解决方案吗?

标签: pythonpandasdataframeindexingmulti-index

解决方案


您可以使用该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

推荐阅读