Accessing property of object stored in Dataframe

notverygood :
class Eq(object):
    price = 2

    # The class "constructor" - It's actually an initializer 
    def __init__(self, price):
        self.price = price

    def get_price():
        return price

d = {'name': ['cac40', 'ftse100'], 'col2': [Eq, Eq]}
df = pd.DataFrame(data=d)

The above builds a Dataframe containing objects in col2,

I would like to access the price property of my objects, and put that in a new column of my dataframe.

I can't seem to be able to access the object though.

Closest I got is df['price'] = df['col2'].values[0].price, but of course this only gets the price property of the first row.

How can I get the price for all the rows?

Thanks

LTheriault :

Generally, if you're trying to create a new column in a DataFrame and methods like this aren't working, it's not a bad idea to look for a way to use the "apply" function. You should be able to tackle your problem this way:

df['price'] = df['col2'].apply(lambda x: x.price)

Though this gets you what you want, why are you storing your object directly within the DataFrame? There might be a more optimal way to get data from your objects into it depending on your reasoning.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=220258&siteId=1