Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从数据帧列的列中dict_Python_Pandas_Dictionary_Tuples - Fatal编程技术网

Python 从数据帧列的列中dict

Python 从数据帧列的列中dict,python,pandas,dictionary,tuples,Python,Pandas,Dictionary,Tuples,如何从dataframe的列创建字典。以下是测试代码: import pandas as pd df = pd.DataFrame({ 'c0': ['A','A','B'], 'c1': ['b','c','d'], 'c2': [1, 3,4], 'c3': [5,7,8]}) 输出: c0 c1 c2 c3 0 A b 1 5 1 A c 3 7 2 B d 4 8 我想从,比如,key:(c0,c1)和val

如何从dataframe的列创建字典。以下是测试代码:

import pandas as pd
df = pd.DataFrame({
    'c0': ['A','A','B'],
    'c1': ['b','c','d'],
    'c2': [1, 3,4],
    'c3': [5,7,8]})
输出:

  c0 c1  c2  c3
0  A  b   1   5
1  A  c   3   7
2  B  d   4   8
我想从,比如,key:(c0,c1)和value:(c2)中获得一本字典

我是这样做的

dict(zip(zip(df['c0'], df['c1']), df['c2']))
您可以与-
多索引一起使用
创建
元组

print (df.set_index(['c0','c1'])['c2'].to_dict())
{('B', 'd'): 4, ('A', 'b'): 1, ('A', 'c'): 3}
print (df.set_index(['c0','c1'])['c2'].to_dict())
{('B', 'd'): 4, ('A', 'b'): 1, ('A', 'c'): 3}