python - 如何将模型对象列表转换为 Pandas 数据框?

标签 python numpy pandas

我有一个此类的对象数组

class CancerDataEntity(Model):

    age = columns.Text(primary_key=True)
    gender = columns.Text(primary_key=True)
    cancer = columns.Text(primary_key=True)
    deaths = columns.Integer()
    ...

打印出来的数组是这样的

[CancerDataEntity(age=u'80-85+', gender=u'Female', cancer=u'All cancers (C00-97,B21)', deaths=15306), CancerDataEntity(...

我想将其转换为数据框,以便以更适合我的方式使用它 - 聚合、计数、求和等。 我希望这个数据框看起来像这样:

     age     gender     cancer     deaths
0    80-85+  Female     ...        15306
1    ...

有没有办法使用 numpy/pandas 轻松实现这一点,而无需手动处理输入数组?

最佳答案

一个更简洁的方法是在你的类上定义一个 to_dict 方法,然后使用 pandas.DataFrame.from_records

class Signal(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def to_dict(self):
        return {
            'x': self.x,
            'y': self.y,
        }

例如

In [87]: signals = [Signal(3, 9), Signal(4, 16)]

In [88]: pandas.DataFrame.from_records([s.to_dict() for s in signals])
Out[88]:
   x   y
0  3   9
1  4  16

关于python - 如何将模型对象列表转换为 Pandas 数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34997174/

相关文章:

python-3.x - 如何在标志从 0 变为 1 之前和之后提取行

python - 如何循环多个 DataFrame 并生成多个 csv?

python - 更改默认 python 后 netplan 不工作

python - 树形 View 鼠标位置python

python - 使用 _leftonly 或 _rightonly 中的值填充 2 列上合并的 Df 外部的缺失值

python - Pandas Groupby 和 sum 有两个变量-

python - 如何根据条件聚合函数?

python - 防止 OS X 使用 Python 进入休眠状态?

python - Python 中的三角网格查询

image-processing - 在numpy中使用as_strided函数滑动窗口?