从嵌套元组键控的python字典重建矢量字段

时间:2016-07-20 15:56:01

标签: python pandas dictionary nested tuples

有以下形式的字典:

vector_dict =  {((3, 4), 2): 4678, 
               ((0, 2), 1): 0,
               ...
                }

嵌套在元组中的元组对应于xy坐标。下一部分是一个整数,其中可能的值为n = 0,1,2,3代表四个主要方向。键入的值代表一定程度。 所以第一个键值对变为: 矢量[1,0],位于x = 3,y = 4,缩放4,678。 我尝试过使用熊猫,但是我无法理解它,如何以可用的方式正确地提取它。 后来我想把它绘制成与右边的一样,但完全填满了主板: enter image description here

1 个答案:

答案 0 :(得分:1)

查看Series constructor以从dict加载数据。然后,您可以unstack获取轴1的方向。最后,convert将位置索引转换为MultiIndex

d = {((3, 4), 2): 4678, ((0, 2), 1): 0}
df = pd.Series(d).unstack()
df.index = pd.MultiIndex.from_tuples(df.index, names=['x', 'y'])

print(df)

产量

       1       2
x y             
0 2  0.0     NaN
3 4  NaN  4678.0