Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas and calling function on an object

I have a column of type Object, and I want to access a property of the object into another column.

import pandas as pd

class foo(object):
    @property
    def value(self):
        return "bar"


if __name__ == "__main__":
    a = [foo(), foo(), foo()]
    df = pd.DataFrame(data=a, columns=['test'])
    df['value'] = df['test'].value

This fails with the following error:

AttributeError: 'Series' object has no attribute 'value'

Is there a way to call a property or function on a class to populate a new column?

like image 462
code base 5000 Avatar asked Sep 02 '25 16:09

code base 5000


1 Answers

class foo(object):
    @property
    def value(self):
        return "bar"


if __name__ == "__main__":
    a = [foo(), foo(), foo()]
    df = pd.DataFrame(data=a, columns=['test'])
    df['value'] = df['test'].apply(lambda x: x.value)

df

enter image description here

like image 73
piRSquared Avatar answered Sep 04 '25 04:09

piRSquared