【发布时间】:2018-09-25 01:58:48
【问题描述】:
我有一个如下所示的数据框 (df1):
id detail
78 [{}{}{}{}{}]
120 [{}{}{}{}{}]
110 [{}{}{}{}{}]
109 [{}{}{}{}{}]
109 [{}{}{}{}{}]
79 [{}{}{}{}{}]
详细信息列包含一个字典列表,每个字典如下所示:
{'y1': 549, 'score': 1, 'x2': 630, 'frame': 1054, 'y2': 564, 'x1': 602, 'visibility': 0.0, 'class': 5}
我需要将此信息提取到具有以下格式的 CSV 中:
frame, id, x1, y1, x2, y2, score, class, visibility
另外,提取出来的数据中的x2和y2应该是这样的:
x2_new = x2 + x1 = 630 + 602 = 1232
y2_new = y2 + y1 = 564 + 549 = 1113
预期输出(假设提供的dict在df1的第一行):
1054, 78, 602, 549, 1232, 1113, 1, 5, 0.0
我已尝试使用此代码根据详细信息列创建新的 df,但出现错误:
for i in finaldftoconvert['id']:
for k in finaldftoconvert[['detail'][['id']==i]]:
df = pd.DataFrame(k)
print df
错误:
main.py:267: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
for k in finaldftoconvert[['detail'][['id']==i]]:
Traceback (most recent call last):
File "main.py", line 268, in <module>
df = pd.DataFrame(k)
File "/usr/lib/python2.7/dist-packages/pandas/core/frame.py", line 305, in __init__
raise PandasError('DataFrame constructor not properly called!')
pandas.core.common.PandasError: DataFrame constructor not properly called!
【问题讨论】:
-
为什么不将
detail列转换为另一个数据框(因为它是一个字典列表),然后在索引上与id合并?新的数据框将更易于使用并执行您的必要操作。 -
@panktijk 我已经编辑了我的问题以包含我刚刚尝试过的内容。您对如何将详细信息列转换为 df 有任何建议吗?以及如何确保新 df 中的每一行都有正确的对应 indexID?
-
你能发布你的脚本来生成你的样本
df吗?
标签: python pandas dictionary dataframe python-2.x