Fix Python – Conditional with statement in Python

Is there a way to begin a block of code with a with statement, but conditionally?
Something like:
if needs_with():
with get_stuff() as gs:

# do nearly the same large block of stuff,
# involving gs or not, depending on needs_with()

To clarify, one scenario would have a block encased in the with statement, while another possibility would be th….

Fix Python – Conditional Replace Pandas

I have a DataFrame, and I want to replace the values in a particular column that exceed a value with zero. I had thought this was a way of achieving this:
df[df.my_channel > 20000].my_channel = 0

If I copy the channel into a new data frame it’s simple:
df2 = df.my_channel

df2[df2 > 20000] = 0

This does exactly what I want, but seems not to wor….

Fix Python – Why is the use of len(SEQUENCE) in condition values considered incorrect by Pylint?

Considering this code snippet:
from os import walk

files = []
for (dirpath, _, filenames) in walk(mydir):
# More code that modifies files
if len(files) == 0: # <-- C1801 return None I was alarmed by Pylint with this message regarding the line with the if statement: [pylint] C1801:Do not use len(SEQUENCE) as condition value The rule C18....

Fix Python – Replace all elements of Python NumPy Array that are greater than some value

I have a 2D NumPy array and would like to replace all values in it greater than or equal to a threshold T with 255.0. To my knowledge, the most fundamental way would be:
shape = arr.shape
result = np.zeros(shape)
for x in range(0, shape[0]):
for y in range(0, shape[1]):
if arr[x, y] >= T:
result[x, y] = 255

What is the mo….