DataFrame to Json Using First Col as Key and Second as Value DataFrame to Json Using First Col as Key and Second as Value pandas pandas

DataFrame to Json Using First Col as Key and Second as Value


Use Series.to_json and if necessary change key value add rename:

print (k.set_index('A').rename(columns={'B':'index1'}).to_json()){"index1":{"1":"a","2":"b","3":"c","4":"d"}}

If need export to file:

k.set_index('A').rename(columns={'B':'index1'}).to_json('file.json')


Although what I am writing is not the answer to the question asked, still I am providing a solution to a small problem I was facing which I googled and reached here.

Problem: how to create a dictionary from a panda data frame with a column as the key and constant value (1 in my case) as the, you guessed it, value.

Solution:

f = pd.Series(data = [1]*df.shape[0],index=df['col_name'])x = f.to_json(orient='columns')

Output:

{"one":1, "two":1, "three": 1}

Why would I do that?Because search in the dictionary is highly optimized (Yeah I can use set as well)

P.S. Novice in Python so please be gentle with me :).