如果 pandas dataframe.loc 位置不存在,则返回默认值 [英] return default if pandas dataframe.loc location doesn't exist

查看:420
本文介绍了如果 pandas dataframe.loc 位置不存在,则返回默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己在尝试引用之前经常必须检查数据框中是否存在列或行.例如,我最终添加了很多代码,例如:

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:

if 'mycol' in df.columns and 'myindex' in df.index: x = df.loc[myindex, mycol]
else: x = mydefault

有没有什么办法可以更好地做到这一点?例如,我可以在任意对象上执行 x = getattr(anobject, 'id', default) - 在 Pandas 中是否有类似的东西?真的有什么方法可以更优雅地完成我正在做的事情吗?

Is there any way to do this more nicely? For example on an arbitrary object I can do x = getattr(anobject, 'id', default) - is there anything similar to this in pandas? Really any way to achieve what I'm doing more gracefully?

推荐答案

系列:

所以你可以这样做:

df.mycol.get(myIndex, NaN)

示例:

In [117]:

df = pd.DataFrame({'mycol':arange(5), 'dummy':arange(5)})
df
Out[117]:
   dummy  mycol
0      0      0
1      1      1
2      2      2
3      3      3
4      4      4

[5 rows x 2 columns]
In [118]:

print(df.mycol.get(2, NaN))
print(df.mycol.get(5, NaN))
2
nan

这篇关于如果 pandas dataframe.loc 位置不存在,则返回默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆