英文:
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'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论