[英]'dict of list of dict' to dataframe
I have a dict of list of dict我有一个字典列表的字典
{
'Col1Name': [{'date': '2020', 'value': '1111'},
{'date': '2019', 'value': '2222'},
{'date': '2018', 'value': '3333'}],
'Col2Name': [{'date': '2020', 'value': '777'},
{'date': '2018', 'value': '999'}]
}
How can I import it elegantly into a dataframe, bearing in mind there may be missing values?我怎样才能优雅地将它导入到数据框中,记住可能有缺失值?
The end result should look something like: (or transposed, doesnt matter)最终结果应该是这样的:(或转置,无所谓)
2020 2019 2018
Col1Name 1111 2222 3333
Col2Name 777 nan 999
Here is a way using pandas.concat
and a small comprehension:这是使用pandas.concat
和一个小理解的方法:
import pandas as pd
pd.concat({c: pd.DataFrame(l).set_index('date').T
for c,l in d.items()}).droplevel(1)
Output:输出:
date 2020 2019 2018
Col1Name 1111 2222 3333
Col2Name 777 NaN 999
Input:输入:
d = {
'Col1Name': [{'date': '2020', 'value': '1111'},
{'date': '2019', 'value': '2222'},
{'date': '2018', 'value': '3333'}],
'Col2Name': [{'date': '2020', 'value': '777'},
{'date': '2018', 'value': '999'}]
}
Assuming the dictionary d
we can use a comprehension to get the dictionary into an appropriate format, then pass to DataFrame.from_dict
:假设字典d
我们可以使用DataFrame.from_dict
将字典转换为适当的格式,然后传递给DataFrame.from_dict
:
df = pd.DataFrame.from_dict(
{k: {v['date']: v['value'] for v in lst} for k, lst in d.items()},
orient='index'
)
df
: df
:
2020 2019 2018
Col1Name 1111 2222 3333
Col2Name 777 NaN 999
We can remove orient='index'
if wanting the other way:如果想要另一种方式,我们可以删除orient='index'
:
df = pd.DataFrame.from_dict(
{k: {v['date']: v['value'] for v in lst} for k, lst in d.items()}
)
df
: df
:
Col1Name Col2Name
2020 1111 777
2019 2222 NaN
2018 3333 999
Setup:设置:
import pandas as pd
d = {
'Col1Name': [{'date': '2020', 'value': '1111'},
{'date': '2019', 'value': '2222'},
{'date': '2018', 'value': '3333'}],
'Col2Name': [{'date': '2020', 'value': '777'},
{'date': '2018', 'value': '999'}]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.