从python对象创建系列,包括其@property

从python对象创建系列,包括其@property,python,pandas,Python,Pandas,要从通用对象创建pandas.Series,可以使用以下方法: import datetime class Test(object): def __init__(self): self.creation = datetime.datetime.now() a = Test() c = pandas.Series(a.__dict__) 这将产生一个系列,描述为 creation 2017-12-17 09:51:48.157503 dtype: datetime

要从通用对象创建
pandas.Series
,可以使用以下方法:

import datetime

class Test(object):
    def __init__(self):
        self.creation = datetime.datetime.now()

a = Test()
c = pandas.Series(a.__dict__)
这将产生一个系列,描述为

creation   2017-12-17 09:51:48.157503
dtype: datetime64[ns]
如果对象包含使用
@property
创建的“属性”,则此操作失败,如下所示

class Test(object):
    def __init__(self):
        self.creation = datetime.datetime.now()

    @property
    def as_string(self):
        return 'Test at {}'.format(self.creation)

a = Test()
c = pandas.Series(a.__dict__) # same as above

对象的属性如何包含在
系列中?或者有没有更简单的方法从通用对象(包括其属性)创建
系列

def data_properties(obj):
    def _props(obj):
        for attr in dir(obj):
            if attr.startswith('__'):
                continue
            val = getattr(obj, attr)
            if not callable(val):
                yield (attr, val)
    return dict(_props(obj))
您可以这样使用它:

import datetime
import pandas


class Foo(object):
    def __init__(self):
        self.x = datetime.datetime.now()

    @property
    def y(self):
        return 5

    def method(self, x):
        return self.y * x


f = Foo()
pd.Series(data_properties(f))
# x    2017-12-17 07:09:20.694000
# y                             5
# dtype: object

这种方法的好处是,如果对结果系列中的内容有其他限制,则可以轻松修改
\u props
生成器来微调结果。

从语义上考虑这一点。。。将这些不同的属性放在一个系列中有多大用处?@cᴏʟᴅsᴘᴇᴇᴅ: 这应该是一个MCVE。实际上,它有点复杂:有一个包含属性的数据对象列表。这些应该包含在数据框中。哦。。。好吧,这里有一种肮脏的方法:
pd.Series([getattr(a,x)代表dir(a)中的x,如果不是x.startswith('''.'))
。想不出更好的方法。请看这里:并稍微修改一下if语句。顺便说一句,请记住@property实际上是类的属性,而不是实例(例如,尝试
Test.\uu dict\uuu
并查看结果)。