How to convert pandas dataFrame to sparse dictionary dictionaries, where only indexes of some clipping are shown. In the toy example below, I need indexes for each column whose values ββare> 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')
This gives:
dfasdict = {'cell_1': {'gene_a': -1, 'gene_b': 0, 'gene_c': 0}, 'cell_2': {'gene_a': 1, 'gene_b': -1, 'gene_c': -1}}
But the desired result is a sparse dictionary, where only values ββless than zero are shown:
desired = {'cell_1': {'gene_a': -1}, 'cell_2': {'gene_b': -1, 'gene_c': -1}}
I can do some processing to change the dfasdict dictionary after creation, but I want to do the conversion in the same step, since the processing subsequently involves iterating over very large dictionaries. Is it possible to do this in pandas?
source share