How can I add an 'if' statement in a dataframe so that I check there are rows so I don't run into an indexing error?

huangapple go评论71阅读模式
英文:

How can I add an 'if' statement in a dataframe so that I check there are rows so I don't run into an indexing error?

问题

以下是已翻译的代码部分:

has_primary_reopen = market_info.loc[before_primary_close, "market_state"].iloc[-1] == 'CTS'
if market_info.loc[before_primary_close, "market_state"].empty:
    # 在这里添加你的处理逻辑,如果上面的查询返回一个空的DataFrame

请告诉我如果你需要更多的帮助。

英文:

So I have the following pandas dataframe query:

has_primary_reopen = market_info.loc[before_primary_close, "market_state"].iloc[-1] == 'CTS'

For the above, I am getting an indexing error, because

market_info.loc[before_primary_close, "market_state"]

returns an empty dataframe.

So I want to add an if statement to check that if the above returns an empty dataframe, then don't execute the top query.

Is this possible?

答案1

得分: 1

是的,您可以这样做:

if not market_info.loc[before_primary_close, "market_state"].empty:
    has_primary_reopen = market_info.loc[before_primary_close, "market_state"].iloc[-1] == 'CTS'
英文:

Yes, you can do it like this:

if not market_info.loc[before_primary_close, "market_state"].empty:
    has_primary_reopen = market_info.loc[before_primary_close, "market_state"].iloc[-1] == 'CTS'

huangapple
  • 本文由 发表于 2023年7月6日 21:12:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76629226.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定