DataFrame to JSON format, using column value as value

27 views Asked by At

I want to output the format of JSON, which is like:

{"553588913747808256":"rumour","524949003834634240":"rumour","553221281181859841":"rumour","580322346508124160":"non-rumour","544307417677189121":"rumour"}

Here, I have a df_prediction_with_id dataFrame and I set_index using the id_str:

df_prediction_with_id

                   rumor_or_not
id_str  
552800070199148544  non-rumour
544388259359387648  non-rumour
552805970536333314  non-rumour
525071376084791297  rumour
498355319979143168  non-rumour

What I've tried is to use DataFrame.to_json.

json = df_prediction_with_id.to_json(orient='index')

What I've got is:

{"552813420136128513":{"rumor_or_not":"non-rumour"},"544340943965409281":{"rumor_or_not":"non-rumour"}}

Is there any way that I could directly use the value in the column as the value? Thanks.

1

There are 1 answers

0
Andrej Kesely On

You can simply select the column and call .to_json():

print(df_prediction_with_id["rumor_or_not"].to_json())

Prints:

{"552800070199148544":"non-rumour","544388259359387648":"non-rumour","552805970536333314":"non-rumour","525071376084791297":"rumour","498355319979143168":"non-rumour"}