How to create a dictionary from columns of pandas dataframe. here is test code:
import pandas as pd
df = pd.DataFrame({
'c0': ['A','A','B'],
'c1': ['b','c','d'],
'c2': [1, 3,4],
'c3': [5,7,8]})
Output:
c0 c1 c2 c3
0 A b 1 5
1 A c 3 7
2 B d 4 8
I would like to obtain a dictionary from, say, key:(c0, c1) and value:(c2)
{('A', 'b'): 1, ('A', 'c'): 3, ('B', 'd'): 4}
You can use set_index
with Series.to_dict
- MutiIndex
creates tuples
:
print (df.set_index(['c0','c1'])['c2'].to_dict())
{('B', 'd'): 4, ('A', 'b'): 1, ('A', 'c'): 3}
这是我做的
dict(zip(zip(df['c0'], df['c1']), df['c2']))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.