Python data frame to dictionary by index variables (i,j)

Viewed 122

I’d like to convert a Python data frame (pandas or other) into a dictionary but the key should be the position (i,j). For example, have a dataframe like:

col1 col2 col3
7 1 2
8 9 6
4 7 5

I'd like to return a dictionary with the key as the position of the value, so the 2nd row, 3rd column would be stored in a dictionary like below.

{(1,2): 6}

Is there a built-in function for this? Or do I need to iterate over the entire data frame? I have not yet found a way to get the position into a dictionary. From other threads, I've seen that you can extract the index with something like this (dataframe called 'df'):

df.stack().index.tolist()
2 Answers

you need to iterate over all lines

Something like this:

d = {'col1': [1, 2, 3], 'col2': [4, 5, 6], 'col3': [7, 8, 9]}
df = pd.DataFrame(data=d)
df

   col1 col2 col3
0   1    4    7
1   2    5    8
2   3    6    9

for i in range(len(df)):
    for j in range(len(df.columns)):
        print({(i,j):df.iloc[i,j]})

output:

{(0, 0): 1}
{(0, 1): 4}
{(0, 2): 7}
{(1, 0): 2}
{(1, 1): 5}
{(1, 2): 8}
{(2, 0): 3}
{(2, 1): 6}
{(2, 2): 9}

from there you can append each element to a bigger dictionary

Let's use a list comprehension to make generating the keys simple.

data = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]

data_dict = {}

for key in [(x, y) for x in range(3) for y in range(3)]:
    data_dict[key] = data[key[1]][key[0]]

Python 2.7+ provides a more elegant solution to this with dictionary comprehensions.

data = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]

data_dict = {(x, y): data[y][x] for x in range(3) for y in range(3)}
Related