1

我想输出 JSON 的格式,比如:

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

在这里,我有一个df_prediction_with_id数据框,我set_index使用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

我尝试过的是使用DataFrame.to_json

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

我所拥有的是:

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

有什么方法可以直接使用列中的值作为值?谢谢。

4

1 回答 1

1

您可以简单地选择列并调用.to_json()

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

印刷:

{"552800070199148544":"non-rumour","544388259359387648":"non-rumour","552805970536333314":"non-rumour","525071376084791297":"rumour","498355319979143168":"non-rumour"}
于 2021-04-16T16:39:52.337 回答