Home > Back-end >  Is there a way to create key-value paired dict from panda dataframe using index and column name as k
Is there a way to create key-value paired dict from panda dataframe using index and column name as k

Time:10-12

I want to convert pandas dataframe to a key value pair dictionary by combining index and column name as key. Is there a easy way to do it?

Before:

             T1      T2  
    apple    5       1   
    pear     2       1.5  
    banana   10      12    

After:

{'apple_T1': 5,
 'apple_T2': 1,
 'pear_T1': 2,
  ...
 'banana_T2':12
 }

Thanks a lot!

CodePudding user response:

In one step:

{f"{k}_{row}": v for row, data in df.iterrows() for k, v in data.items()}

CodePudding user response:

Use DataFrame.to_dict followed by a dictionary comprehension:

import pandas as pd

data = [[5, 1], [2, 1.5], [10, 12]]
df = pd.DataFrame(data=data, columns=["T1", "T2"], index=["apple", "pear", "banana"])

result = { f"{kout}_{kin}" : value for kout, d in df.to_dict("index").items() for kin, value in d.items()}
print(result)

Output

{'apple_T1': 5, 'apple_T2': 1.0, 'pear_T1': 2, 'pear_T2': 1.5, 'banana_T1': 10, 'banana_T2': 12.0}

CodePudding user response:

You can use df.to_dict(orient='index')

Set your dataframe:

df = pd.DataFrame(
    columns=["T1", "T2"], 
    data=[[5,1], [2, 1.5], [10, 12]], 
    index=["apple", "pear", "banana"]
)

Apply .to_dict method:

d = df.to_dict(orient='index')
result = {f"{k1}_{k2}": v for k1 in d for k2, v in d[k1].items()}

Result:

{'apple_T1': 5,
 'apple_T2': 1,
 'banana_T1': 10,
 'banana_T2': 12,
 'pear_T1': 2,
 'pear_T2': 1.5}

CodePudding user response:

A direct way is to loop through all index and columns, and define the dictionary items one by one:

df = pd.DataFrame([[5, 1], [2, 1.5], [10, 12]], 
                  columns=['T1', 'T2'], 
                  index=['apple', 'pear', 'banana'])
new_dict = {}
for i in df.index:
    for j in df.columns:
        new_dict[i   '_'   j] = df.loc[i, j]
print(new_dict)

Output is

{'apple_T1': 5,
 'apple_T2': 1.0,
 'pear_T1': 2,
 'pear_T2': 1.5,
 'banana_T1': 10,
 'banana_T2': 12.0}

CodePudding user response:

You can use df.iterrows() but you need be careful to get what you want:

>>> {f'{row}_{k}':v for row, col in df.iterrows() for k,v in list(col.items())[1:]}

{'apple_T1': 5,
 'apple_T2': 1.0,
 'pear_T1': 2,
 'pear_T2': 1.5,
 'banana_T1': 10,
 'banana_T2': 12.0}
  • Related