return default if pandas dataframe.loc location doesn't exist

后端 未结 2 594
我寻月下人不归
我寻月下人不归 2021-02-11 14:35

I find myself often having to check whether a column or row exists in a dataframe before trying to reference it. For example I end up adding a lot of code like:

         


        
2条回答
  •  庸人自扰
    2021-02-11 14:57

    Python has this mentality to ask for forgiveness instead of permission. You'll find a lot of posts on this matter, such as this one.

    In Python catching exceptions is relatively inexpensive, so you're encouraged to use it. This is called the EAFP approach.

    For example:

    try:
        x = df.loc['myindex', 'mycol']
    except KeyError:
        x = mydefault
    

提交回复
热议问题