我有一个包含id
的数据框和dicts列表:
df = pd.DataFrame({
'list_of_dicts': [[{'a': 1, 'b': 2}, {'a': 11, 'b': 22}],
[{'a': 3, 'b': 4}, {'a': 33, 'b': 44}]],
'id': [100, 200]
})
我希望将其标准化为:
id a b
0 100 1 2
0 100 3 4
1 200 11 22
1 200 33 44
这大部分都是这样的:
pd.concat([
pd.DataFrame.from_dict(item)
for item in df.list_of_dicts
])
但缺少id
列。
我对可读性最感兴趣。
答案 0 :(得分:1)
这样的事情怎么样:
d = {
'list_of_dicts': [[{'a': 1, 'b': 2}, {'a': 11, 'b': 22}],
[{'a': 3, 'b': 4}, {'a': 33, 'b': 44}]],
'id': [100, 200]
}
df = pd.DataFrame([pd.Series(x) for ld in d['list_of_dicts'] for x in ld])
id = [[x]*len(l) for l,x in zip(d['list_of_dicts'],d['id'])]
df['id'] = pd.Series([x for l in id for x in l])
编辑 - 这是一个更简单的版本
t = [[('id', i)]+list(l.items()) for i in d['id'] for ll in d['list_of_dicts'] for l in ll]
df = pd.DataFrame([dict(x) for x in t])
并且,如果您真的想要id
列,则可以从dict
模块将OrderedDict
更改为collections
。
答案 1 :(得分:0)
这就是我所说的不理解
// get all elements
$elements = json_decode($oJSON)->rows[0]->elements;
// get all the distances
// array_map() is useful here b/c there is a 1-1 correspondence between an element and its distance
$distances = array_map(function ($element) {
// convert distance to numeric value to ensure that we are only working with numbers (and not strings)
return (float) preg_replace('/[^\d\.]/','', $element->distance->text);
}, $elements);
// get the maximum value
echo 'Distance in Miles: ' . max($distances);