如何从以键为列和行索引的字典构造pandas DataFrame

How to construct pandas DataFrame from dictionary with key as column and row index

词典

x = {(0,0):1,(0,1):4,(1,0):2,(1,1):5}

x的key同时包含row和col信息,i.g(0,0)为第0行第0列

如何从这种字典中优雅地构造 df ?

最简单的事情是首先制作一个只使用元组作为多索引的系列。然后您可以将 MultiIndex 拆分为列:

>>> x
{(0, 0): 1, (0, 1): 4, (1, 0): 2, (1, 1): 5}
>>> pandas.Series(x).unstack()
   0  1
0  1  4
1  2  5