【问题标题】:Pandas dataframe float index not self-consistent熊猫数据框浮动索引不是自洽的
【发布时间】:2019-12-12 12:36:19
【问题描述】:

我需要/想要在 pandas 中使用浮点索引,但在运行类似这样的操作时出现键错误:

inds = [1.1, 2.2]
cols = [5.4, 6.7]
df = pd.DataFrame(np.random.randn(2, 2), index=inds, columns=cols)
df[df.index[0]]

我看到了一些关于精度的错误,但这不应该有效吗?

【问题讨论】:

    标签: python-3.x pandas dataframe indexing


    【解决方案1】:

    您会得到KeyError,因为在这种情况下df[df.index[0]] 会尝试访问带有标签1.1 的列——此处不存在。

    您可以使用lociloc 根据索引访问行:

    import numpy as np
    import pandas as pd
    
    inds = [1.1, 2.2]
    cols = [5.4, 6.7]
    df = pd.DataFrame(np.random.randn(2, 2), index=inds, columns=cols)
    
    # to access e.g. the first row use
    df.loc[df.index[0]]
    # or more general
    df.iloc[0]
    
    # 5.4    1.531411
    # 6.7   -0.341232
    # Name: 1.1, dtype: float64
    

    原则上,如果可以,请避免使用 equal comparisons 处理浮点数,原因是您已经遇到过:精度。显示给您的1.1 可能是计算机的!= 1.1 - 仅仅是因为理论上这需要无限精度。大多数情况下,它会起作用,因为某些公差检查会启动;例如,如果比较数字的差是

    【讨论】:

    • 非常感谢您的清晰解释。我现在明白这是一个愚蠢的错误,但是作为熊猫的新手,我看不到它!
    • @j_bio:很高兴我能帮上忙!而且您必须进行浮动比较,除了我链接的 SO 帖子之外,还有 numpy.isclose - 以防万一 ;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 2018-02-02
    • 2012-12-20
    相关资源
    最近更新 更多