Home > Net >  Converting a PD DF to a dictionary
Converting a PD DF to a dictionary

Time:03-18

I have a pd dataframe as seen in image: image of data

imported via the pd.read_csv method.

I would like to convert it to a dictionary, where the key is 'Countries', and the value is a list of the numbers 1 to 300. How is the best way to do this? I have tried other methods listed on stack but since my df doesn't have column headings it is not working

CodePudding user response:

Something like this should do what your question asks:

d = {row[1]:list(row[2:]) for row in df.itertuples()}

Here is sample code showing the above in the context of your question:

records = [
    ['afghanistan', -0.9,-0.7,-0.5,-0.3,-0.1,0.1,0.3,0.5,0.7,0.9],
    ['albania', -0.9,-0.7,-0.5,-0.3,-0.1,0.1,0.3,0.5,0.7,0.9],
    ['algeria', -0.9,-0.7,-0.5,-0.3,-0.1,0.1,0.3,0.5,0.7,0.9],
    ['andorra', -0.9,-0.7,-0.5,-0.3,-0.1,0.1,0.3,0.5,0.7,0.9]
]

import pandas as pd
df = pd.DataFrame(records)
print(df)

d = {row[1]:list(row[2:]) for row in df.itertuples()}
print()
[print(f"{k} : {v}") for k, v in d.items()]

Output:

            0    1    2    3    4    5    6    7    8    9    10
0  afghanistan -0.9 -0.7 -0.5 -0.3 -0.1  0.1  0.3  0.5  0.7  0.9
1      albania -0.9 -0.7 -0.5 -0.3 -0.1  0.1  0.3  0.5  0.7  0.9
2      algeria -0.9 -0.7 -0.5 -0.3 -0.1  0.1  0.3  0.5  0.7  0.9
3      andorra -0.9 -0.7 -0.5 -0.3 -0.1  0.1  0.3  0.5  0.7  0.9

afghanistan : [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9]
albania : [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9]
algeria : [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9]
andorra : [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9]
  • Related