1

I currently have a column of string values which looks like this:

d = {'col1': '(100,200),(150,124),(135,137)'}

And I need to change this to float values to become this:

d = {'col1': [(100,200),(150,124),(135,137)]}

Any help would be much appreciated.

cs95
  • 379,657
  • 97
  • 704
  • 746
NZ_DJ
  • 341
  • 2
  • 13

2 Answers2

4

Let's try using ast.literal_eval. You can wrap your strings in braces and safe-eval them:

import ast
d = {k : ast.literal_eval(f'[{v}]') for k, v in d.items()}

pd.DataFrame(d)

         col1
0  (100, 200)
1  (150, 124)
2  (135, 137)
cs95
  • 379,657
  • 97
  • 704
  • 746
-1

Firstly, add sqare brackets around the string: {'col1': '[(100, 200), (150, 124), (135, 137)]'}

Later on, eval () that string.

d['col1'] = '[' + d['col1'] + ']'
d['col1'] = eval(d['col1'])

print(d)
# {'col1': [(100, 200), (150, 124), (135, 137)]}

pd.DataFrame(d)
Melvin Abraham
  • 2,870
  • 5
  • 19
  • 33