Home > Blockchain >  How to transform a dataframe to a dictionary with key tuples
How to transform a dataframe to a dictionary with key tuples

Time:08-27

how can I convert a dataframe to a dictionary with the keys as a tuple?

    0            1             2                
0   0           4733          456           
1   5223        0             5680          
2   901         5635          0         

like this:

i!=j

{(0, 1): 4733,
 (0, 2): 456,
 (1, 0): 5223,
 (1, 2): 5680,
 (2, 0): 901,
 (2, 1): 5635
}

CodePudding user response:

You can do something like this:

import pandas as pd
df = pd.DataFrame({0: [0, 5223, 901], 1: [4733, 0, 5635], 2: [456, 5680, 0]})

result = {}
for k, v in df.to_dict(orient='list').items():
    for idx, value in enumerate(v):
        if k != idx:
            result[(idx, k)] = value
print(result)

Output:

{
    (1, 0): 5223, 
    (2, 0): 901, 
    (0, 1): 4733, 
    (2, 1): 5635, 
    (0, 2): 456, 
    (1, 2): 5680
}

CodePudding user response:

You can use stack() and to_dict()

df.stack().to_dict()

Output:

{(0, '0'): 0,
 (0, '1'): 4733,
 (0, '2'): 456,
 (1, '0'): 5223,
 (1, '1'): 0,
 (1, '2'): 5680,
 (2, '0'): 901,
 (2, '1'): 5635,
 (2, '2'): 0}

It appears that perhaps the 0 values are removed. If this is the case the below should work:

df.stack().loc[lambda x: x.ne(0)].to_dict()

Output:

{(0, '1'): 4733,
 (0, '2'): 456,
 (1, '0'): 5223,
 (1, '2'): 5680,
 (2, '0'): 901,
 (2, '1'): 5635}
  • Related