数据帧索引存在性检查

2024-09-29 21:37:06 发布

您现在位置:Python中文网/ 问答频道 /正文

当我执行以下代码时,它会生成水平线(根据需要),但仅当此位置(索引位置可用)出现在我的\u数据(我的\u数据已过滤/已选择)中时。你知道吗

plt.axhline(y=my_data.loc[6805], color='green', linestyle='dashed')

我想写一些像:

If my_data.loc[6805] is not None:
   plt.axhline(y=my_data.loc[6805], color='green', linestyle='dashed')

如何检查索引位置是否可用?你知道吗


Tags: 数据代码dataifismynotplt
1条回答
网友
1楼 · 发布于 2024-09-29 21:37:06

1]错误异常处理

  • 您可以使用错误异常处理来实现这一点
  • 如果该位置不存在,那么您将得到一个KeyError:
  • 试一试就是你要找的

    try:
        mplt.axhline(y=my_data.loc[6805], color='green', linestyle='dashed')
    except:
        pass
    

2]检查6805是否为索引

  • 您可以做的另一件事是签入6805 exist作为索引

    if 6805 in my_data.index.tolist():
        mplt.axhline(y=my_data.loc[6805], color='green', linestyle='dashed')
    

3]检查行数

  • 您可以检查总行数是否大于或等于6805

    if my_data.shape[0] >= 6805 :
        mplt.axhline(y=my_data.loc[6805], color='green', linestyle='dashed')
    

相关问题 更多 >

    热门问题