Creating a table using a tuple dictionary (Python Pandas)

I have a dict with a tuple key:

td=[((1, 1), 1), ((1, 2), 2), ((1, 3), 1) ((2, 1), 1), ((2, 2), 5), ((3, 2), 2]

I want to create a table as shown below: (using tuple as an index)

     1     2     3

1    1     2     1

2    2     5     2

3    1     0     0 

How to create this table using python?

I tried pd.MultiIndex, but it did not work.

Thank.

+4
source share
3 answers

I think so.

pd.Series(dict(td)).reset_index()
Out[115]: 
   level_0  level_1  0
0        1        1  1
1        1        2  2
2        1        3  1
3        2        1  1
4        2        2  5
5        3        1  1
6        3        2  2
+4
source

I do not see the need MultiIndexhere.

Option 1
Flatten before calling pd.DataFrame. You can generalize this with unpacking the arguments *-

pd.DataFrame([list(x) + y for x, *y in td])

   0  1  2
0  1  1  1
1  1  2  2
2  1  3  1
3  2  1  1
4  2  2  5
5  3  2  2

Option 2
A little cooler using pd.concat-

df = pd.DataFrame(td)

        0  1
0  (1, 1)  1
1  (1, 2)  2
2  (1, 3)  1
3  (2, 1)  1
4  (2, 2)  5
5  (3, 2)  2

pd.concat([pd.DataFrame(df.iloc[:, 0].tolist()), df.iloc[:, 1:]], axis=1)

   0  1  1
0  1  1  1
1  1  2  2
2  1  3  1
3  2  1  1
4  2  2  5
5  3  2  2
+4
source

Let's try this:

Correct some data:

td=[((1, 1), 1), ((1, 2), 2), ((1, 3), 1), ((2, 1), 1), 
    ((2, 2), 5), ((3, 2), 2), ((3, 1), 1)]

Smooth tuples

l = [(i[0],i[1],v) for i,v in td]
lol = [list(e) for e in l]

Create and modify data form

pd.DataFrame(lol).set_index([1,0]).rename_axis([None,None]).unstack()[2]\
  .fillna(0).astype(int)

Conclusion:

   1  2  3
1  1  1  1
2  2  5  2
3  1  0  0

To expand the data format:

pd.DataFrame(lol).set_index([1,0]).rename_axis([None,None]).unstack()[2]\
  .reindex(index=np.arange(1,10), columns=np.arange(1,10)).fillna(0).astype(int)

Conclusion:

   1   2  3  4  5  6  7  8  9
1  9   0  0  0  0  0  0  0  0
2  0  10  0  0  0  0  0  0  0
3  0   1  0  1  0  0  0  0  0
4  0   0  0  1  0  0  0  0  0
5  0   0  0  0  1  1  0  0  0
6  0   0  0  0  0  1  0  0  0
7  0   0  0  0  0  0  0  0  0
8  0   0  0  0  0  0  0  0  0
9  0   0  0  0  0  0  0  0  0
+3
source

Source: https://habr.com/ru/post/1690732/


All Articles