从对象创建数据框

时间:2014-09-06 23:21:39

标签: python pandas

我收到了一组对象,需要将它们的属性保存在数据框中。这些对象都具有相同的属性,但值不同。

我在尝试

dicts = [x.__dict__ for x in objectCollection]
df = pd.concat(dicts)

但那会给我

TypeError: cannot concatenate a non-NDFrame object

以下为了复制目的,我的r对象(它包含4个词典)

In[94]: r
Out[94]: 
[{'JB': 0.5261750636924186,
  'JBar': 0.5261750636925998,
  'U': 0.3294737627050343,
  'VB': 0,
  'VBar': 0,
  'WB': 0.3879376586708586,
  'WBar': 0.38793765867087865,
  'YB': 0.48616322013005736,
  'YBar': 0.4861632201302899,
  'pB': 1,
  'pBar': 1.0000000000002274,
  'theta': 30.452217802750784,
  'thetaB': 15.226108901371752,
  'thetaBar': 15.226108901379034,
  'u': 0.027673559739652746,
  'vB': 0.4213606342845696,
  'vBar': 0.4213606342847711,
  'wB': 0.40542217802756686,
  'wBar': 0.4054221780275895},
 {'JB': 0.591730026927601,
  'JBar': 0.5888459364503311,
  'U': 0.3574380470030322,
  'VB': 0,
  'VBar': 0,
  'WB': 0.4133529860815169,
  'WBar': 0.42286537327529117,
  'YB': 0.4450754942945968,
  'YBar': 0.4420654404537785,
  'pB': 1,
  'pBar': 1.0068090684451363,
  'theta': 35.72497708330982,
  'thetaB': 17.92309565619036,
  'thetaBar': 17.801881427119454,
  'u': 0.02414497177678684,
  'vB': 0.43275263877136705,
  'vBar': 0.4298259246315051,
  'wB': 0.43134506957181085,
  'wBar': 0.44209406710077587},
 {'JB': 0.46774949304709174,
  'JBar': 0.783373528458816,
  'U': 0.4259229207218348,
  'VB': 0,
  'VBar': 0,
  'WB': 0.47789508661595614,
  'WBar': 0.5129644238839255,
  'YB': 0.5805290540642507,
  'YBar': 0.39605190181885574,
  'pB': 1,
  'pBar': 1.4657903456561598,
  'theta': 39.39305475097706,
  'thetaB': 12.929841051766449,
  'thetaBar': 26.463213699210606,
  'u': 0.02341904411689341,
  'vB': 0.302804518015738,
  'vBar': 0.6197431690965912,
  'wB': 0.4948305475091409,
  'wBar': 0.5414095820747569},
 {'JB': 0.5246012340492012,
  'JBar': 0.8731358801035817,
  'U': 0.4675627478175433,
  'VB': 0,
  'VBar': 0,
  'WB': 0.5155637079793887,
  'WBar': 0.5645778456068301,
  'YB': 0.5312340916010532,
  'YBar': 0.3593021864121634,
  'pB': 1,
  'pBar': 1.4785161674233223,
  'theta': 45.929330938192074,
  'thetaB': 15.162892309068837,
  'thetaBar': 30.766438629123233,
  'u': 0.020410094185461556,
  'vB': 0.3094760601521056,
  'vBar': 0.6279459101716279,
  'wB': 0.5334306672268627,
  'wBar': 0.5960674456434281}]

2 个答案:

答案 0 :(得分:7)

pandas DataFrame constructor确实接受了一个dicts列表,并可以将它们解析为一个DataFrame。这对我有用

df = pd.DataFrame(r)

这给了我一个数据框,其中dict键为列,其属性为行。这是你想要实现的目标吗?

答案 1 :(得分:4)

在列表解析中尝试pd.DataFrame构造:

import pandas as pd
pd.concat([pd.DataFrame(x[1], index=[x[0]]) for x in enumerate(r)])