我有一个四列的数据框架。我想把这个DataFrame转换成一个python字典。我希望第一列的元素是键,而同一行中其他列的元素是值。

DataFrame:

    ID   A   B   C
0   p    1   3   2
1   q    4   3   2
2   r    4   0   9  

输出应该是这样的:

字典:

{'p': [1,3,2], 'q': [4,3,2], 'r': [4,0,9]}

当前回答

遵循以下步骤:

假设你的数据框架如下:

>>> df
   A  B  C ID
0  1  3  2  p
1  4  3  2  q
2  4  0  9  r

1. 使用set_index将ID列设置为数据帧索引。

    df.set_index("ID", drop=True, inplace=True)

2. 使用orient=index参数将索引作为字典键。

    dictionary = df.to_dict(orient="index")

结果如下:

    >>> dictionary
    {'q': {'A': 4, 'B': 3, 'D': 2}, 'p': {'A': 1, 'B': 3, 'D': 2}, 'r': {'A': 4, 'B': 0, 'D': 9}}

3.如果您需要将每个示例作为列表运行以下代码。确定列的顺序

column_order= ["A", "B", "C"] #  Determine your preferred order of columns
d = {} #  Initialize the new dictionary as an empty dictionary
for k in dictionary:
    d[k] = [dictionary[k][column_name] for column_name in column_order]

其他回答

如果你不介意字典值是元组,你可以使用itertuples:

>>> {x[0]: x[1:] for x in df.itertuples(index=False)}
{'p': (1, 3, 2), 'q': (4, 3, 2), 'r': (4, 0, 9)}

尝试使用Zip

df = pd.read_csv("file")
d= dict([(i,[a,b,c ]) for i, a,b,c in zip(df.ID, df.A,df.B,df.C)])
print d

输出:

{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}

DataFrame.to_dict()将DataFrame转换为字典。

例子

>>> df = pd.DataFrame(
    {'col1': [1, 2], 'col2': [0.5, 0.75]}, index=['a', 'b'])
>>> df
   col1  col2
a     1   0.1
b     2   0.2
>>> df.to_dict()
{'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}}

详见本文档

也可以使用字典理解和iterrows()方法来获得所需的输出。

result = {row.ID: [row.A, row.B, row.C] for (index, row) in df.iterrows()}

一本字典应该是:

{'red': '0.500', 'yellow': '0.250', 'blue': '0.125'}

被要求出一个数据框架,像这样:

        a      b
0     red  0.500
1  yellow  0.250
2    blue  0.125

最简单的方法是:

dict(df.values)

工作代码片段如下:

import pandas as pd
df = pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]})
dict(df.values)