Reputation: 183
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
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
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