I have a dataframe with 2 columns and I want to add the new column;
This new column should be updated based on the list that I have:
list = [0,1,2,3,6,7,9,10]
The new column is only updated with the list value if the flag (in col2) is 1. If flag is 0, do not populate row in new column.
Current DF
+-------------+---------+
| context | flag |
+-------------+---------+
| 0 | 1 |
| 0 | 1 |
| 0 | 0 |
| 2 | 1 |
| 2 | 1 |
| 2 | 1 |
| 2 | 1 |
| 2 | 0 |
| 4 | 1 |
| 4 | 1 |
| 4 | 0 |
+-------------+---------+
Desired DF
+-------------+---------+-------------+
| context | flag | new_context |
+-------------+---------+-------------+
| 0 | 1 | 0 |
| 0 | 1 | 1 |
| 0 | 0 | |
| 2 | 1 | 2 |
| 2 | 1 | 3 |
| 2 | 1 | 6 |
| 2 | 1 | 7 |
| 2 | 0 | |
| 4 | 1 | 9 |
| 4 | 1 | 10 |
| 4 | 0 | |
+-------------+---------+-------------+
Right now, I loop through the indices of the list and assign the list value to the new_context column. Then I increment to go through the list. The values are populated in the correct spots but they all say 0. I don't believe it's iterating through the list properly.
list_length = len(list)
i=0
for i in range(list_length])):
df["new_context"] = [list[i] if ele == 0 else "" for ele in df["flag"]]
if df["flag"] == 0: i+=1
I have also tried to iterate through a entire dataframe, however I think it's just applying the same list value (first list value of 0)
i=0
for index, row in df.iterrows():
df["new_context"] = [list[i] if ele == 0 else "" for ele in df["flag"]]
if row['flag'] == 0: i+=1
How can I use the next list value to populate the new column where the flag=1? It seems i+=1 is not working.