将Pandas DataFrame转换为字典

COS*_*STA 126 python dictionary dataframe pandas

我有一个包含四列的DataFrame.我想将此DataFrame转换为python字典.我想要第一列keys的元素和同一行中其他列的元素values.

数据帧:

    ID   A   B   C
0   p    1   3   2
1   q    4   3   2
2   r    4   0   9  
Run Code Online (Sandbox Code Playgroud)

输出应该是这样的:

字典:

{'p': [1,3,2], 'q': [4,3,2], 'r': [4,0,9]}
Run Code Online (Sandbox Code Playgroud)

Ale*_*ley 257

to_dict()方法将列名设置为字典键,因此您需要稍微重塑您的DataFrame.将"ID"列设置为索引然后转置DataFrame是实现此目的的一种方法.

to_dict()还接受一个'orient'参数,您需要该参数才能输出每列的值列表.否则,{index: value}将为每列返回表单的字典.

可以使用以下行完成这些步骤:

>>> df.set_index('ID').T.to_dict('list')
{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}
Run Code Online (Sandbox Code Playgroud)

如果需要不同的字典格式,这里是可能的东方参数的示例.考虑以下简单的DataFrame:

>>> df = pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]})
>>> df
        a      b
0     red  0.500
1  yellow  0.250
2    blue  0.125
Run Code Online (Sandbox Code Playgroud)

然后选项如下.

dict - 默认值:列名是键,值是索引的字典:数据对

>>> df.to_dict('dict')
{'a': {0: 'red', 1: 'yellow', 2: 'blue'}, 
 'b': {0: 0.5, 1: 0.25, 2: 0.125}}
Run Code Online (Sandbox Code Playgroud)

list - 键是列名,值是列数据列表

>>> df.to_dict('list')
{'a': ['red', 'yellow', 'blue'], 
 'b': [0.5, 0.25, 0.125]}
Run Code Online (Sandbox Code Playgroud)

系列 - 比如'list',但值是Series

>>> df.to_dict('series')
{'a': 0       red
      1    yellow
      2      blue
      Name: a, dtype: object, 

 'b': 0    0.500
      1    0.250
      2    0.125
      Name: b, dtype: float64}
Run Code Online (Sandbox Code Playgroud)

split - 将列/数据/索引拆分为键,值分别为列名,数据值分别按行和索引标签

>>> df.to_dict('split')
{'columns': ['a', 'b'],
 'data': [['red', 0.5], ['yellow', 0.25], ['blue', 0.125]],
 'index': [0, 1, 2]}
Run Code Online (Sandbox Code Playgroud)

记录 - 每一行都成为一个字典,其中键是列名,值是单元格中的数据

>>> df.to_dict('records')
[{'a': 'red', 'b': 0.5}, 
 {'a': 'yellow', 'b': 0.25}, 
 {'a': 'blue', 'b': 0.125}]
Run Code Online (Sandbox Code Playgroud)

index - 类似于'records',但是一个字典字典,其中键作为索引标签(而不是列表)

>>> df.to_dict('index')
{0: {'a': 'red', 'b': 0.5},
 1: {'a': 'yellow', 'b': 0.25},
 2: {'a': 'blue', 'b': 0.125}}
Run Code Online (Sandbox Code Playgroud)

  • 这将是一个班轮:`df.set_index('ID').T.to_dict('list')` (10认同)
  • `df.to_dict('records')` 是大多数现代软件想要的与类似 `json` 模式匹配的字典的方式 (4认同)

小智 58

应该像这样的字典:

{'red': '0.500', 'yellow': '0.250, 'blue': '0.125'}
Run Code Online (Sandbox Code Playgroud)

需要从数据帧中提取,例如:

        a      b
0     red  0.500
1  yellow  0.250
2    blue  0.125
Run Code Online (Sandbox Code Playgroud)

最简单的方法是这样做:

dict(df.values)
Run Code Online (Sandbox Code Playgroud)

下面的工作片段:

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

  • 整洁的 !但它仅适用于两列数据框。 (2认同)

小智 17

尝试使用 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
Run Code Online (Sandbox Code Playgroud)

输出:

{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}
Run Code Online (Sandbox Code Playgroud)


Far*_*eki 13

跟着这些步骤:

假设您的数据框如下:

>>> df
   A  B  C ID
0  1  3  2  p
1  4  3  2  q
2  4  0  9  r
Run Code Online (Sandbox Code Playgroud)

1. set_index用于将ID列设置为数据框索引.

    df.set_index("ID", drop=True, inplace=True)
Run Code Online (Sandbox Code Playgroud)

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

    dictionary = df.to_dict(orient="index")
Run Code Online (Sandbox Code Playgroud)

结果如下:

    >>> dictionary
    {'q': {'A': 4, 'B': 3, 'D': 2}, 'p': {'A': 1, 'B': 3, 'D': 2}, 'r': {'A': 4, 'B': 0, 'D': 9}}
Run Code Online (Sandbox Code Playgroud)

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]
Run Code Online (Sandbox Code Playgroud)

  • 对于最后一点似乎你可以更简单地使用dict理解来替换for循环+列表理解(3行 - > 1).无论哪种方式,虽然有选择很好,但最重要的答案要短得多. (2认同)

ksi*_*ndi 10

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

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


Vic*_*art 7

对于我的使用(带有 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),
 ... }
Run Code Online (Sandbox Code Playgroud)

附录

后来我又回到了这个问题,从事其他但相关的工作。这是一种更接近地反映[优秀]接受的答案的方法。

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
...
Run Code Online (Sandbox Code Playgroud)

将 Pandas 数据帧转换为 [list], {dict}, {dict of {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},
 ... }
Run Code Online (Sandbox Code Playgroud)

就我而言,我想做同样的事情,但是使用 Pandas 数据框中选定的列,因此我需要对列进行切片。有两种方法。

  1. 直接地:

(请参阅:将 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},
 ... }
Run Code Online (Sandbox Code Playgroud)
  1. “间接:”首先,从 Pandas 数据帧中切片所需的列/数据(同样,两种方法),
node_df_sliced = node_df[['kegg_cid', 'name', 'wt', 'vis']]
Run Code Online (Sandbox Code Playgroud)

或者

node_df_sliced2 = node_df.loc[:, ['kegg_cid', 'name', 'wt', 'vis']]
Run Code Online (Sandbox Code Playgroud)

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

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},
 ... }
Run Code Online (Sandbox Code Playgroud)