Efficiently replace values from a column to another column Pandas DataFrame

Using np.where is faster. Using a similar pattern as you used with replace: df[‘col1’] = np.where(df[‘col1’] == 0, df[‘col2’], df[‘col1’]) df[‘col1’] = np.where(df[‘col1’] == 0, df[‘col3’], df[‘col1’]) However, using a nested np.where is slightly faster: df[‘col1’] = np.where(df[‘col1’] == 0, np.where(df[‘col2’] == 0, df[‘col3’], df[‘col2’]), df[‘col1’]) Timings Using the following setup to produce a larger … Read more

How can I replace every instance of a pattern in ruby?

String.gsub should do the trick. Quoting docs: gsub(pattern, replacement) → new_str Returns a copy of str with the all occurrences of pattern substituted for the second argument. The pattern is typically a Regexp; if given as a String, any regular expression metacharacters it contains will be interpreted literally, e.g. \\d will match a backlash followed … Read more

Replacing escape characters from JSON

I have found that the easiest and best way to remove all escape characters from your JSON string, is to pass the string into Regex.Unescape() method. This method returns a new string with no ecapes, even \n \t etc, are removed. See this MSDN article for more details: Regex.Unescape Method (String) (System.Text.RegularExpressions)

C# String replace with dictionary

If the data is tokenized (i.e. “Dear $name$, as of $date$ your balance is $amount$”), then a Regex can be useful: static readonly Regex re = new Regex(@”\$(\w+)\$”, RegexOptions.Compiled); static void Main() { string input = @”Dear $name$, as of $date$ your balance is $amount$”; var args = new Dictionary<string, string>( StringComparer.OrdinalIgnoreCase) { {“name”, “Mr … Read more

Efficient Javascript String Replacement

It looks like you want to use a template. //Updated 28 October 2011: Now allows 0, NaN, false, null and undefined in output. function template( templateid, data ){ return document.getElementById( templateid ).innerHTML .replace( /%(\w*)%/g, // or /{(\w*)}/g for “{this} instead of %this%” function( m, key ){ return data.hasOwnProperty( key ) ? data[ key ] : … Read more