How to replace certain values in Tensorflow tensor with the values of the other tensor?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In TensorFlow, the usual way to replace selected tensor values with values from another tensor is tf.where. It performs element-wise selection based on a condition tensor, which makes it ideal for masking, cleanup, and conditional feature construction as long as shapes and dtypes line up correctly.
The Standard Pattern: tf.where
tf.where(condition, x, y) returns elements from x where the condition is true, and from y where the condition is false.
For replacement tasks, x is often the replacement tensor and y is the original tensor.
This says: wherever source equals -1, take the value from replacement; otherwise keep the original value.
Replacing with a Separate Condition Tensor
The condition does not have to come from the source tensor itself. You can compute it elsewhere and use it directly.
This is useful when the mask comes from another model stage or business rule.
Working with Matrices and Higher-Rank Tensors
The same logic works for 2D or higher-dimensional tensors.
As long as the shapes are compatible, TensorFlow applies the selection element by element.
Sparse Index Updates Are a Different Operation
If you already know the exact indices that should change, tf.tensor_scatter_nd_update can be cleaner than building a full boolean mask.
This is not the same as tf.where, but it is often the better tool when the update positions are already known.
Shape and Dtype Rules
Most replacement bugs come from these two issues:
- source and replacement tensors have incompatible shapes
- source and replacement tensors have different dtypes
For example, this is usually a problem:
Make the dtypes explicit before replacement:
Also be careful with broadcasting. TensorFlow may allow it, but the result may not be the element-wise alignment you intended.
A Small Helper Function
Wrapping the pattern once can make data pipelines easier to read and test.
Common Pitfalls
One common mistake is reaching for Python if statements inside tensor code. That does not perform element-wise tensor replacement.
Another issue is relying on broadcasting without checking tensor shapes carefully. The code may run but still produce the wrong alignment.
A third pitfall is using tf.where when you really want sparse index updates. In that case, tf.tensor_scatter_nd_update is usually clearer.
Summary
- Use
tf.wherefor element-wise conditional replacement. - Build a boolean mask that marks the values to replace.
- Keep source, replacement, and condition shapes compatible.
- Match dtypes explicitly to avoid type errors.
- Use
tf.tensor_scatter_nd_updateinstead when you already know exact update indices.

