我有一个四列的数据框架。我想把这个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]}

当前回答

大多数答案都不能处理ID在数据框架中可能存在多次的情况。如果ID可以在Dataframe df中复制,你想使用一个列表来存储值(也就是列表的列表),按ID分组:

{k: [g['A'].tolist(), g['B'].tolist(), g['C'].tolist()] for k,g in df.groupby('ID')}

其他回答

对于我的使用(节点名称与xy位置),我发现@user4179775的答案最有帮助/直观:

import pandas as pd

df = pd.read_csv('glycolysis_nodes_xy.tsv', sep='\t')

df.head()
    nodes    x    y
0  c00033  146  958
1  c00031  601  195
...

xy_dict_list=dict([(i,[a,b]) for i, a,b in zip(df.nodes, df.x,df.y)])

xy_dict_list
{'c00022': [483, 868],
 'c00024': [146, 868],
 ... }

xy_dict_tuples=dict([(i,(a,b)) for i, a,b in zip(df.nodes, df.x,df.y)])

xy_dict_tuples
{'c00022': (483, 868),
 'c00024': (146, 868),
 ... }

齿顶高

后来我又回到这个问题上,进行其他相关的工作。这里有一个更接近公认答案的方法。

node_df = pd.read_csv('node_prop-glycolysis_tca-from_pg.tsv', sep='\t')

node_df.head()
   node  kegg_id kegg_cid            name  wt  vis
0  22    22       c00022   pyruvate        1   1
1  24    24       c00024   acetyl-CoA      1   1
...

转换Pandas数据帧为[list], {dict}, {dict}}的{dict,…

每个接受的答案:

node_df.set_index('kegg_cid').T.to_dict('list')

{'c00022': [22, 22, 'pyruvate', 1, 1],
 'c00024': [24, 24, 'acetyl-CoA', 1, 1],
 ... }

node_df.set_index('kegg_cid').T.to_dict('dict')

{'c00022': {'kegg_id': 22, 'name': 'pyruvate', 'node': 22, 'vis': 1, 'wt': 1},
 'c00024': {'kegg_id': 24, 'name': 'acetyl-CoA', 'node': 24, 'vis': 1, 'wt': 1},
 ... }

在我的例子中,我想做同样的事情,但从Pandas数据框架中选择列,所以我需要对列进行切片。有两种方法。

直接:

(请参阅:将pandas转换为定义键值所使用列的字典)

node_df.set_index('kegg_cid')[['name', 'wt', 'vis']].T.to_dict('dict')

{'c00022': {'name': 'pyruvate', 'vis': 1, 'wt': 1},
 'c00024': {'name': 'acetyl-CoA', 'vis': 1, 'wt': 1},
 ... }

“间接地:”首先,从Pandas数据框架中切片所需的列/数据(同样是两种方法),

node_df_sliced = node_df[['kegg_cid', 'name', 'wt', 'vis']]

or

node_df_sliced2 = node_df.loc[:, ['kegg_cid', 'name', 'wt', 'vis']]

然后可以用来创建字典的字典

node_df_sliced.set_index('kegg_cid').T.to_dict('dict')

{'c00022': {'name': 'pyruvate', 'vis': 1, 'wt': 1},
 'c00024': {'name': 'acetyl-CoA', 'vis': 1, 'wt': 1},
 ... }

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}}

详见本文档

使用这种方法,dataframe的列将是键,而dataframe的系列将是值。

data_dict = dict()
for col in dataframe.columns:
    data_dict[col] = dataframe[col].values.tolist()

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

>>> {x[0]: x[1:] for x in df.itertuples(index=False)}
{'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]