Home > Software engineering >  Replace value with index number if condition is met in pandas
Replace value with index number if condition is met in pandas

Time:10-12

I have this dataframe and I want to replace the value column with a string that contains the index number if the state is "no".

Input:

index state value
1 yes 6
2 no 098
3 no 4
4 yes 123
5 no 7696

Output:

index state value
1 yes 6
2 no F2
3 no F3
4 yes 123
5 no F5

CodePudding user response:

You can check the condition and assign concatenated values using .loc :

df.loc[df['state'].eq('no'), 'value'] = 'F'   df['index'].astype(str)

OUTPUT

   index state value
0      1   yes     6
1      2    no    F2
2      3    no    F3
3      4   yes   123
4      5    no    F5

Or, you can create and store the Boolean mask in a separate variable, then implement:

mask=df['state'].eq('no')
df.loc[mask, 'value'] = 'F'   df.loc[mask, 'index'].astype(str)

CodePudding user response:

You can use np.where:

df['value'] = np.where(df['state'] == 'no', 'F'   df['index'].astype(str), df['value'])
  • Related