如何将模型对象列表转换为pandas数据框? [英] How to convert list of model objects to pandas dataframe?
本文介绍了如何将模型对象列表转换为pandas数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个此类的对象数组
I have an array of objects of this class
class CancerDataEntity(Model):
age = columns.Text(primary_key=True)
gender = columns.Text(primary_key=True)
cancer = columns.Text(primary_key=True)
deaths = columns.Integer()
...
打印后,数组看起来像这样
When printed, array looks like this
[CancerDataEntity(age=u'80-85+', gender=u'Female', cancer=u'All cancers (C00-97,B21)', deaths=15306), CancerDataEntity(...
我想将其转换为数据帧,以便我可以以更适合我的方式进行操作-进行汇总,计数,求和等. 我希望这个数据框看起来像这样:
I want to convert this to a data frame so I can play with it in a more suitable way to me - to aggregate, count, sum and similar. How I wish this data frame to look, would be something like this:
age gender cancer deaths
0 80-85+ Female ... 15306
1 ...
是否有一种方法可以轻松地使用numpy/pandas来实现,而无需手动处理输入数组?
Is there a way to achieve this using numpy/pandas easily, without manually processing the input array?
推荐答案
导致所需结果的代码:
variables = arr[0].keys()
df = pd.DataFrame([[getattr(i,j) for j in variables] for i in arr], columns = variables)
感谢@Serbitar向我指出正确的方向.
Thanks to @Serbitar for pointing me to the right direction.
这篇关于如何将模型对象列表转换为pandas数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文