我有以下測驗代碼
import numpy as np
import pandas as pd
x = np.array([['101', 'title1', 'body1', 'answer1'], ['102', 'title2', 'body2', 'answer2'], ['103', 'title3', 'body3', 'answer3']])
df = pd.DataFrame(x, columns = ['col1', 'col2', 'col3', 'col4'])
df.head()
| col1 |col2 |col3 |col4
---------------------------------
0| 101 |title1 |body1 |answer1
1| 102 |title2 |body2 |answer2
2| 103 |title3 |body3 |answer3
我想要這種格式的 json 輸出
{"index": {"_id": "col1"}}
{"title": "col2", "body": "col3", "answer": "col4"}
喜歡
{"index": {"_id": "101"}}
{"title": "title1", "body": "body1", "answer": "answer1"}
對于資料框中的每一行。
任何人都可以發光嗎?
uj5u.com熱心網友回復:
這并不難,我建議你閱讀圖書館的檔案。
import numpy as np
import pandas as pd
x = np.array([['101', 'title1', 'body1', 'answer1'], ['102', 'title2', 'body2', 'answer2'],
['103', 'title3', 'body3', 'answer3']])
df = pd.DataFrame(x, columns=['col1', 'col2', 'col3', 'col4'])
djson=df.to_json()
print(djson)
uj5u.com熱心網友回復:
拉斐爾的答案可能是解決您的問題的最佳方法(如果您希望逐行進行,您可以在df.transpose之前進行df.to_json());但是,如果您真正想要的是完全按照您的定義定義 json 字串(這與列名不同),您可以執行以下操作:
jsons = []
json_string = '{{"index": {{"_id": "{index}"}}}}{{"title": "{title}", "body": "{body}", "answer": "{answer}"}}'
for row in range(len(df)):
data = [df.iloc[row, x] for x in range(len(df.columns))]
jsons.append(json_string.format(index=data[0],title=data[1],body=data[2], answer=data[3]))
然后獲取jsons變數中的json字串串列。如果您需要轉換為物件,您可以使用 json 庫,并使用json.loads()
uj5u.com熱心網友回復:
創建一個 json 字串,說明您希望輸出在資料幀上的外觀和格式。
對于 curl 操作(使用 ElasticSearch 和 Kibana 時),請確保拆分下面的 json 字串
json_string = '{{"index": {{"_id": "{index}"}}}}{{"title": "{title}", "body": "{body}", "answer": "{answer}"}}'
將在 json 中給出輸出為
{"index": {"_id": "101"}}{"title": "title1", "body": "body1", "answer": "answer1"}
輸出是這樣的
{"index": {"_id": "101"}}
{"title": "title1", "body": "body1", "answer": "answer1"}
利用
json_string1 = '{{"index": {{"_id": "{index}"}}}}'
json_string2 = '{{"title": "{title}", "body": "{body}", "answer": "{answer}"}}'
這是完整的代碼(通過 json.dumps() 后跟 json.loads() 將 json 串列轉換為 json 物件
import numpy as np
import pandas as pd
import json
x = np.array([['101', 'title1', 'body1', 'answer1'], ['102', 'title2', 'body2', 'answer2'], ['103', 'title3', 'body3', 'answer3']])
df = pd.DataFrame(x, columns = ['col1', 'col2', 'col3', 'col4'])
jsons = []
json_string1 = '{{"index": {{"_id": "{index}"}}}}'
json_string2 = '{{"title": "{title}", "body": "{body}", "answer": "{answer}"}}'
for row in range(len(df)):
data = [df.iloc[row, x] for x in range(len(df.columns))]
jsons.append(json_string1.format(index=data[0]))
jsons.append(json_string2.format(title=data[1],body=data[2], answer=data[3]))
with open("filename.json", "w") as fp:
for i in range(len(jsons)):
x = json.dumps(jsons[i])
y = json.loads(x)
fp.write("%s\n" % y)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/518550.html
下一篇:將自定義檔案格式設為json檔案
