0
import json
import pandas as pd

data = {'Product':['Product 2.1.4', 'Product 2.1.5'],
        'Version':['2.1.4', '2.1.5']
}

df = pd.DataFrame(data)

df['regex_value'] = '^.*' + df['Version'] + '[\s-]*$'


di = pd.Series(df.Product.values,index=df.regex_value).to_dict()


print("Printing data frame: \n", df)

print("\nPrinting dictionary: \n",di)

Output shows that there is only 1 backslash in pandas dataframe, but 2 backslashes after conversion to dictionary. How to prevent this or how to change the 2 backslashes in dictionary back to 1 backslash?

Printing data frame: 
          Product Version      regex_value
0  Product 2.1.4   2.1.4  ^.*2.1.4[\s-]*$
1  Product 2.1.5   2.1.5  ^.*2.1.5[\s-]*$

Printing dictionary: 
 {'^.*2.1.4[\\s-]*$': 'Product 2.1.4', '^.*2.1.5[\\s-]*$': 'Product 2.1.5'}

I use the dictionary with regex in another pandas dataframe to replace values and it does not work correctly with 2 backslashes.

df1['new_version'] = df1['old_version'].replace(di,regex=True)
Jerry
  • 31
  • 1
  • 7

0 Answers0