Reputation: 307
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
Upvotes: 2
Views: 2451
Reputation: 631
You can get a list of attribute values from a list of objects like this:
df['price'] = [obj.price for obj in df['col2']]
Upvotes: 1
Reputation: 1240
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.
Upvotes: 5