Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
71 views
in Technique[技术] by (71.8m points)

python - How can I generate a json file in pandas without including the index?

I have an input json file that looks roughly like this

[
  {
    "identifier": "116S5RJ63",
    "containers": [
      {
        "contains": "soap",
        "height": {
          "unit": "FT",
          "value": 12.07123829231181
        },
        "length": {
          "unit": "FT",
          "value": 12.07123829231181
        },
        "quantity": 1,
        "weight": {
          "unit": "volumeUnits",
          "value": 10000
        },
        "width": {
          "unit": "FT",
          "value": 12.07123829231181
        }
      }
    ],{...}]

I read it in using

input_json  = pd.read_json(input_json_file)

I then process the input_json a bit: nothing dramatic, just changing the contents of some fields. Next I try to output the json again as

input_json.to_json(output_file, orient='records', date_format='iso')

but the output looks like this

[
  {
    "index": 28741,
    "identifier": "115JKLJVZ",
     "containers": [
      {
        "contains": "soap",
        "height": {
          "unit": "FT",
          "value": 12.07123829231181
        },
        "length": {
          "unit": "FT",
          "value": 12.07123829231181
        },
        "quantity": 1,
        "weight": {
          "unit": "volumeUnits",
          "value": 10000
        },
        "width": {
          "unit": "FT",
          "value": 12.07123829231181
        }
      }
    ],{...}]

Specifically it now includes the field 'index', which I thought the orient='records' was supposed to deal with. I'm not sure what to do next. Any suggestions?

question from:https://stackoverflow.com/questions/65946445/how-can-i-generate-a-json-file-in-pandas-without-including-the-index

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try input_json.reset_index(drop=True, inplace=True) before saving it to file; this should drop the old index from being added as a column. reset_index documentation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...