我正在創建一個將資料發送到遠程服務器的函式。我目前正在使用 pandas 庫來讀取 CSV 檔案并將資料轉換為資料幀。我需要做的是遍歷該資料幀并將每一行轉換為 JSON 并將它們發送到我的資料庫。
我需要遍歷的原因是太大的資料集(當前發送 100 行 x 21 列)對于 HTML 字串來說太長了。我需要做的是發送回圈并發送大量 10 左右。
以下是我目前所在的位置:
def UploadData(root, self, data):
i = 0
data_arr = []
for row in data:
if i % 5 == 0:
# Add row to array or something
data_arr.append(row)
json_str = data_arr.to_json(orient='records')
url = 'https://newsimland.com/~db/JSON/?tok={"tok":"YOUR TOKEN HERE","cmd":{"STORE":"test_database","VALUE":' json_str '}}'
r = requests.get(url)
else:
# Add row to array
data_arr.append(row)
i = 1
data = r.json()
if r.status_code == 200:
Alert(title="Error", text="Data upload unsuccessful")
else:
Alert(title="Success", text="Data upload successful")
這樣做的問題之一是它.to_json(orient='records')適用于資料幀,而不是我要附加到的陣列。此外,如果原始資料幀少于 5 行,則不會將資料發送到資料庫。
有誰知道我怎么能做到這一點?
uj5u.com熱心網友回復:
如果我理解正確,您希望以 5 行或更少行的部分發送您的 DataFrame。在這種情況下,我建議您按以下方式拆分資料幀,以便將行保留為資料幀,并且您可以使用to_json.
import numpy as np
def UploadData(root, self, data):
size = 5
for chunk in np.split(data, np.arange(size, data.size, size)):
if chunk.size:
json_str = chunk.to_json(orient='records')
# Send your data here!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/343230.html
