'How do I write R like for-loops in Python with indexing and many ifelse statements in pandas dataframes?
I have a specific for loop which I want to translate into Python but realized that Python does not use indexing. I know how to use enumerate() and simpler for loops where there is no deeper purpose with the for loop.
This time, I have a grouped dataframe which needs to iterate from index 2:N and thereby skipping 1st index in R => 0th index in Python.
Basically, I want to look for product number and store number occuring in row i to see if it matches row i-1 and then execute some ifelse statements with values occurring in row i and i-1 from columns in the dataframe.
For loop in R using data.table set() that I want to translate into Python
for(i in 2:nrow(df)) set(df, i, "col_A",
ifelse(df$col_B[i]==df$col_B[i-1] & df$col_C[i]==df$col_C[i-1],
0,
1
)
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
