[英]dict from columns of pandas dataframe columns
How to create a dictionary from columns of pandas dataframe. 如何从pandas数据框的列创建字典。 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) 我想从例如key:(c0,c1)和value:(c2)获取字典
{('A', 'b'): 1, ('A', 'c'): 3, ('B', 'd'): 4}
You can use set_index
with Series.to_dict
- MutiIndex
creates tuples
: 可以将
set_index
与Series.to_dict
MutiIndex
使用MutiIndex
创建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']))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.