pandas和调用对象的函数

时间:2016-10-27 17:47:27

标签: python pandas dataframe

我有一个Object类型的列,我想要将该对象的属性访问到另一列。

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

此操作失败,并显示以下错误:

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

有没有办法在类上调用属性或函数来填充新列?

1 个答案:

答案 0 :(得分:4)

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