'Is there a way to create key-value paired dict from panda dataframe using index and column name as key?
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!
Solution 1:[1]
In one step:
{f"{row}_{k}": v for row, data in df.iterrows() for k, v in data.items()}
Solution 2:[2]
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}
Solution 3:[3]
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}
Solution 4:[4]
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}
Solution 5:[5]
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}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Dani Mesejo |
| Solution 3 | Carmoreno |
| Solution 4 | Black Raven |
| Solution 5 | I'mahdi |
