I have a pandas dataframe with a column containing a class with a bunch of attributes. I wish to expand some of those attributes into new columns. I have some working code but it looks a bit nasty and uses an eval. What is the more pythonic way to do this
import pandas as pd
#Boilerplate for minimal, reproducible example
class cl:
class inner:
na1 = "nested atribute one"
na2 = "nested atribute two"
def __init__(self, name):
self.name = name
a1 = "atribute one"
a2 = "atribute one"
inner_atts = inner()
class_object1 = cl("first")
class_object2 = cl("second")
data = [class_object1,class_object2]
data_frame = pd.DataFrame(data,columns=['class object'])
####################
info_to_get = {'name','a1','a2','inner_atts.na1','inner_atts.na2'}
for x in info_to_get:
sr = 'y.{0}'.format(x)
data_frame['{0}'.format(x)] = data_frame['class object'].apply(lambda y: eval(sr,{'y':y}))
print(data_frame)