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.
–
–
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.