Ryszard Eggink
Ryszard Eggink

Reputation: 183

Update value in a row if value in another row is equal to a string

Let's say we have a DataFrame:

df = pd.DataFrame({'index': [0, 1, 2],
                   'values1': ['name', 'a', 'x'],
                   'values2': ['PST', 'b', 'y'],
                   'values3': ['noPST', 'c', 'z'],
                   'values4': ['noPST', 'd', 'h'],
                   'values5': ['PST', 'e', 'j']})
index values1 values2 values3 values4   values5
  0    name      PST     noPST    noPST    PST
  1    a         b        c       d        e
  2     x        y        z       h        j

How can I replace all values in row indexed 2 to v if the value in the first row (indexed 0) is equal to PST.

As a result I would like to get:

index values1 values2 values3 values4   values5
  0    name      PST     noPST    noPST    PST
  1    a         b        c       d        e
  2     x        v        z       h        v

Upvotes: 1

Views: 228

Answers (2)

gilf0yle
gilf0yle

Reputation: 1102

this is a bit similar to enke answer but a bit more straight forward as extracting column names is not essential, can be done for self explanatory code !!works!!

df.loc[2,df.loc[0]=='PST']='V'

output:

   index values1 values2 values3 values4 values5
0      0    name     PST   noPST   noPST     PST
1      1       a       b       c       d       e
2      2       x       V       z       h       V

Upvotes: 1

user7864386
user7864386

Reputation:

You can index the columns with a boolean Series and then use loc:

relevant_cols = df.columns[df.loc[0]=='PST']
df.loc[2, relevant_cols] = 'v'

Output:

   index values1 values2 values3 values4 values5
0      0    name     PST   noPST   noPST     PST
1      1       a       b       c       d       e
2      2       x       v       z       h       v

Upvotes: 4

Related Questions