Pandas数据帧成稀疏字典

2024-10-04 11:31:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我如何将pandas数据帧转换成一个稀疏字典字典,其中只显示一些截止点的索引。在下面的玩具示例中,我只需要值大于0的每列的索引

import pandas as pd

table1 = [['gene_a', -1 , 1], ['gene_b', 1, 1],['gene_c', 0, -1]]
df1 = pd.DataFrame(table)
df1.columns = ['gene','cell_1', 'cell_2']
df1 = df1.set_index('gene')
dfasdict = df1.to_dict(orient='dict')

这样可以得到:

dfasdict = {'cell_1': {'gene_a': -1, 'gene_b': 0, 'gene_c': 0}, 'cell_2': {'gene_a': 1, 'gene_b': -1, 'gene_c': -1}}

但所需的输出是稀疏字典,其中只显示小于零的值:

desired = {'cell_1': {'gene_a': -1}, 'cell_2': {'gene_b': -1, 'gene_c': -1}}

我可以在创建之后进行一些处理来更改dfasdict字典,但是我希望在同一步骤中进行转换,因为之后的处理涉及到迭代非常大的字典。在大熊猫体内,这一切都有可能吗?在


Tags: 数据import示例dataframepandas字典ascell
2条回答

删除代码的最后一行并添加这一行。在

from pandas import compat

def to_dict_custom(data):
    return dict((k, v[v<0].to_dict()) for k, v in compat.iteritems(data))

dfasdict = to_dict_custom(df1)
print dfasdict

产生了

^{pr2}$

第3&4行灵感来自here请检查。在

此结果使用字典理解来生成结果。对于cell_1cell_2中的每一列,它将查找小于(lt)0的列,并将结果转换为字典。在

>>> {col: df1.loc[df1[col].lt(0), col].to_dict() for col in ['cell_1', 'cell_2']}
{'cell_1': {'gene_a': -1}, 'cell_2': {'gene_c': -1}}

为了帮助理解这里发生了什么:

^{pr2}$

相关问题 更多 >