Home > Net >  Convert string type to Instance type
Convert string type to Instance type

Time:01-04

I have a dict(image attached below): [1]: https://i.stack.imgur.com/n3SYv.png

The keys of the dict is a dataframe. When trying to upload this dict to json I had to convert column a to string type from interval type. But when I want to use the json I want to convert the values of column a back to interval type. Below are the things I've tried:

k = dict.keys()
for keys in k:
   dict[keys]["a"] = dict[keys]["a"].astype("interval")

But it throws the below error: TypeError: type <class 'str'> with value (-inf, -9999999.0] is not an interval

Can you please help me with the way to convert column a values from string to Interval types?

CodePudding user response:

To convert a string to an instance of a class in Python, you will first need to define the class and have a string that contains the data that you want to initialize the instance with. You can then use the "ast.literal_eval()" function from the ast module to evaluate the string as a Python expression and create an instance of the class.

CodePudding user response:

(See Security of Python's eval() on untrusted strings?)

>>> class Foo(object):
...     pass
... 
>>> eval("Foo")
<class '__main__.Foo'>
  • Related