添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
想出国的拐杖  ·  python dataframe ...·  3 周前    · 
健壮的皮带  ·  python DataFrame循环读取 ...·  3 周前    · 
没有腹肌的蚂蚁  ·  Reading an excel file ...·  1 周前    · 
善良的红茶  ·  SQLPrepare 函数 - ODBC ...·  2 月前    · 
玩足球的烤土司  ·  Technology技术分享·  4 月前    · 
温柔的豆浆  ·  Solved: Re: Exporting ...·  5 月前    · 
发怒的花卷  ·  CWE - CWE-135: ...·  11 月前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm trying to filter a df column and rename certain rows depending on next/previous row value.

This code (without AND though) worked for me for other sorting in the same df:

for row in df.index:
    if df['col1'][row] == 'b' and df['col1'][row+1] =='name':
        df['col1'][row +1] = 'name1' 
        df['col1'][row +2] = 'name2'

Here it throws KeyError 9 and I assume it's because of AND condition in row+1. Is there any way to workaround?

This issue is because the index is out of range.

When in the for loop run with "row = 8", the last row for dataframe, therefore "df['col']['row+1'] is invalid.

Because row+1 = 9 is out of range. "KeyError 9" means cannot find the index "9" in your dataframe.

i think it still return the error when the loop go to the last row, can you try with "for row in range(0,5):" to check that if it is the problem. – Trường Thuận Nguyễn Sep 17, 2021 at 20:04 @Irrats If this still doesn't resolve the problem for you, please edit the question to add in any missing information (for example, you have shown some sample data, but you haven't show us what df.index looks like, or mentioned the dimensions of the data in the question. You should try to reduce the problem down to a minimal reproducible example and post the minimal data and code (ideally as data, not as a picture of data) that can reproduce your problem. – David Buck Sep 18, 2021 at 5:36

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.