GC2023
GC2023

Reputation: 71

Get value in other cell in same row when if condition in for loop is met

I would like to loop through a dataframe column and when a specific value is reached, I would like to save the value in another column I created and called "index" in the same row. Here is an example df:

index  value
  0      a
  2      b
  3      c
  9      a
  23     d

i trying to code it like this:

for value in df["value"]:
    if value == "a":
       current_index = #get value in "index" in current row

I cannot simply save all indices of rows where the value is "a" because the rest of my code wouldn't work then.

I think this should be pretty easy but somehow I cannot find the solution.

Thank you all for your support!

Upvotes: 1

Views: 1125

Answers (1)

Anurag Dabas
Anurag Dabas

Reputation: 24314

IIUC:

try via boolean masking and loc accessor:

out=df.loc[df['value'].eq('a'),'index'].tolist()

output of out:

[0, 9]

OR

If you want to create a column then:

df['newcol']=df['index'].where(df['value'].eq('a'))

output of df:

    index   value   newcol
0   0       a       0.0
1   2       b       NaN
2   3       c       NaN
3   9       a       9.0
4   23      d       NaN

Upvotes: 1

Related Questions