Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.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 从数据帧值创建字典_Python_Python 3.x_Pandas - Fatal编程技术网

Python 从数据帧值创建字典

Python 从数据帧值创建字典,python,python-3.x,pandas,Python,Python 3.x,Pandas,我想创建一个字典,其中键是来自数据帧的一列的值,值来自对应行中的另一列 下面是一个数据帧示例: df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD')) df.head() A B C D 0 34 99 78 0 1 31 47 44 22 2 53 38 11 27 3 86 84 81 87 4 57 4 23 46

我想创建一个字典,其中键是来自数据帧的一列的值,值来自对应行中的另一列

下面是一个数据帧示例:

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
df.head()

    A   B   C   D
0   34  99  78  0
1   31  47  44  22
2   53  38  11  27
3   86  84  81  87
4   57  4   23  46
我想得到这样一个字典,a值作为键,C值作为字典值:

{34: 78, 31: 44, 53: 11, 86: 81,57: 23}

您将如何执行此操作?

您可以从包含键和元组的元组数组中创建dict。因此,在使用
zip
函数将值转换为元组后,您可以在这里直接使用dict构造函数

In [12]: dict(zip(df['A'], df['C']))                                                                                                                                                                               
Out[12]: {34: 78, 31: 44, 53: 11, 86: 81, 57: 23}

另一种方法


这回答了你的问题吗?
df.set_index('A')['C'].to_dict()
# {34: 78, 31: 44, 53: 11, 86: 81, 57: 23}