Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas – can't strip '}' by str.strip function

i have below sample data in csv file.

string,class,id
"{""key1"":""value1"":""key2"":""value2""}",classA,idA
"{""key3"":""value3"":""key4"":""value4""}",classB,idB
...

when I use strip function to strip the right brace }, it fails to strip.

df.string =  df.string.apply(lambda x: x.strip('}'))

but when i tried to strip the left brace {, it works.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

what’s the root cause here?

>Solution :

Do you read the file with doublequote=False, this should work fine with the default doublequote=True?

import io

data = '''string,class,id
"{""key1"":""value1"":""key2"":""value2""}",classA,idA
"{""key3"":""value3"":""key4"":""value4""}",classB,idB'''

df = pd.read_csv(io.StringIO(data), sep=',', doublequote=True)

df['string'] = df['string'].str.strip('}')

print(df)

Output:

                             string   class   id
0  {"key1":"value1":"key2":"value2"  classA  idA
1  {"key3":"value3":"key4":"value4"  classB  idB
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading