ohai
ohai

Reputation: 183

Extract value of a particular column name in pandas

Suppose I have dataframe:

    aiman       air    ajang    akhir    aktif     alat
0    0           0       0     0.0196    0.0117   0.0115
1   0.0297    0.0318   0.0223     0        0         0

and I want to convert that to be json file, and don't want to take a column with a value of 0, like this:

[
    {
     akhir:0.0196,
     aktif:0.0117,
     alat:0.0115
    },
    {
     aiman:0.0297,
     air: 0.0318,
     ajang: 0.0223
    }
] 

I hope my question is clear enough. Anyone has an idea how to get that json file?

Upvotes: 1

Views: 41

Answers (1)

jezrael
jezrael

Reputation: 862511

Convert values to list of dictionaries and then remove values with 0:

d = [{k:v for k, v in x.items() if v != 0} for x in df.to_dict('r')]
print (d)
[{'akhir': 0.0196, 'aktif': 0.0117, 'alat': 0.0115}, 
 {'aiman': 0.0297, 'air': 0.0318, 'ajang': 0.0223}]

Upvotes: 1

Related Questions