progresshans
progresshans

Reputation: 105

Convert Pandas DataFrame specific columns to dict(json format)

I have a Dataframe with four columns - key, value, min, max:

                   key       value  min   max
0              is_open        true    0     9
56              is_run       false    0     9
54          can_delete        true    0     9
53             content      Hello!    0     9
52        chat-profile     Discord    0     9

I am trying to convert it to a dict(json format) with the following format - {"key": "value", "key": "value", ... }:

{
    'is_open': 'true',
    'is_run': 'false',
    'can_delete': 'true',
    'content': 'Hello!',
    'chat-profile': 'Discord'
}

So i wrote code like this.

result = {}
for _, row in df[['key', 'value']].iterrows():
    result[row['key']] = row['value']

However, this code seems to become slower as the number of rows increases.
Is there any faster and better way?

Upvotes: 2

Views: 820

Answers (1)

BoomBoxBoy
BoomBoxBoy

Reputation: 1885

You can do that with either of the following

# 6.44 µs on 10 million rows
d = df.set_index('key')['value'].to_dict()

# 6.68 µs on 10 million rows
d = dict(zip(df['key'], df['value']))

@Psidom's solution seems to be a little bit faster when testing on a dataframe with 10 million rows

Upvotes: 1

Related Questions