这个问题已经在这里有了答案: > Construct pandas DataFrame from items in nested dictionary 3个
嗨,我有如图所示的字典词典(复制的示例).我想将其转换为一个高的DataFrame.
字典示例:
{'Jill': {'Avenger: Age of Ultron': 7.0,'Django Unchained': 6.5,'Gone Girl': 9.0,'Kill the Messenger': 8.0},'Toby': {'Avenger: Age of Ultron': 8.5,'Django Unchained': 9.0,'Zoolander': 2.0}}
预期的高数据帧如下所示:
Column1 Column2 Column3
Jill Avenger: Age of Ultron 7.0
Jill Django Unchained 6.5
Jill Gone Girl 9.0
Jill Kill the Messenger 8.0
Toby Avenger: Age of Ultron 8.5
Toby Django Unchained 9.0
Toby Zoolander 2.0
我在下面尝试过,它使字典的主键作为第一列,但不能使其成为高个数据框:
pd.DataFrame.from_dict(d,orient='index')
最佳答案
d = {'Jill': {'Avenger: Age of Ultron': 7.0,'Zoolander': 2.0}}
df = pd.DataFrame.from_dict(d).reset_index()
df = pd.melt(df,id_vars=["index"],var_name="By",value_name="score").dropna()