Home > Mobile >  Selected column in a pandas dataframe to newline delimited json
Selected column in a pandas dataframe to newline delimited json

Time:11-04

df = pd.DataFrame({"id":[123,465,978,505,567], "feature":[1.1,1.2,1.2,6.7,8.9]})

I try to only save a json file just for the id column. However, it seems that there is no column selection in the to_json function.

My ideal result is like

{"id":123}
{"id":465}
{"id":978}
{"id":505}
{"id":567} 

I've tried method 1: df.to_json("temp.json", orient="records", lines=True)

result 1:

{"id":123,"feature":1.1}
{"id":465,"feature":1.2}
{"id":978,"feature":1.2}
{"id":505,"feature":6.7}
{"id":567,"feature":8.9}

method 2: df['id'].to_json("temp.json", orient="records", lines=True)

result 2:

123
465
978
505
567

CodePudding user response:

Try to use df[["id"]]:

df[["id"]].to_json("temp.json", orient="records", lines=True)

saves temp.json:

{"id":123}
{"id":465}
{"id":978}
{"id":505}
{"id":567}
  • Related