Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - json array to pandas dataframe and write it to csv

I have a json array like below and i wanted to convert into a pandas dataframe and write it into a csv finally.

I have a number column from the list as l[0] and i want to add this to the df and write everything into csv.

[{'value': ' 5644427289 ', 'page_num': '0', 'score': '0.9', 'coord': '["(Decimal('90.000')", " Decimal('257.163')", " Decimal('362.250')", " Decimal('307.683'))"]', 'height': '50.51999999999998', 'width': '272.25'}]

I wanted to write only value,page_num and score to my df and also i have additionally one more l[0] to my df and finally write it into csv.

for s in range(len(json_obj)):

    op_json='{"value":"' + str(json_obj[s]["value"]) + '","page_num":"' + str(json_obj[s]["page_num"]) + '", "score":"' + str(json_obj[s]["score"]) + '"}'
            print(op_json)
            df =pd.DataFrame(None)
            df = json_normalize(op_json)
            if os.path.exists(r'/data/results/0101/a.csv'):
                df.to_csv(r'/data/results/0101/a.csv',mode='a', index=False, header=False)
            else:
                df.to_csv(r'/data/results/0101/a.csv', mode='a', index=False, header=True)

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

1 Answer

0 votes
by (71.8m points)
l = [{'value': ' 5644427289 ', 'page_num': '0', 'score': '0.9', 'coord': '["(Decimal('90.000')", " Decimal('257.163')", " Decimal('362.250')", " Decimal('307.683'))"]', 'height': '50.51999999999998', 'width': '272.25'}]

pd.DataFrame(l)[['value', 'page_num', 'score']].to_csv('file.csv',index=False)
          value page_num score
0   5644427289         0   0.9

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...