Fix Python – Replace and overwrite instead of appending

I have the following code:
import re
#open the xml file for reading:
file = open(‘path/test.xml’,’r+’)
#convert to string:
data = file.read()
file.write(re.sub(r”ABC(\s+)(.*)“,r”ABC\1\2“,data))
file.close()

where I’d like to replace the old content that’s in the file with the new content. Ho….

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 – Speed up millions of regex replacements in Python 3

I have two lists:

a list of about 750K “sentences” (long strings)
a list of about 20K “words” that I would like to delete from my 750K sentences

So, I have to loop through 750K sentences and perform about 20K replacements, but ONLY if my words are actually “words” and are not part of a larger string of characters.
I am doing this by pre-compilin….

Fix Python – Removing a list of characters in string

I want to remove characters in a string in python:
string.replace(‘,’, ”).replace(“!”, ”).replace(“:”, ”).replace(“;”, ”)…

But I have many characters I have to remove. I thought about a list
list = [‘,’, ‘!’, ‘.’, ‘;’…]

But how can I use the list to replace the characters in the string?
….

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….

Fix Python – Finding and replacing elements in a list

I have to search through a list and replace all occurrences of one element with another. So far my attempts in code are getting me nowhere, what is the best way to do this?
For example, suppose my list has the following integers
>>> a = [1,2,3,4,5,1,2,3,4,5,1]

and I need to replace all occurrences of the number 1 with the value 10 so the output I….