[英]How do I transfer json objects into an excel file using python?
如何使用 python 將 json 對象傳輸到 excel 文件中?
我目前正在進行一個項目,以建立一個教授數據庫。 我能夠遍歷 for 循環中的每個鏈接並獲取此類數據:
{"total": 1, "offset": 0, "data": [{"authorId": "118985833", "name": "Krystle K. Madrid"}]}
{"total": 1, "offset": 0, "data": [{"authorId": "107707217", "name": "S. N. Kirnon"}]}
{"total": 5, "offset": 0, "data": [{"authorId": "121754802", "name": "Jason L. Jarvis"}, {"authorId": "143879405", "name": "J. Jarvis"}, {"authorId": "145088127", "name": "J. Jarvis"}, {"authorId": "31259897", "name": "J. W. Jarvis"}, {"authorId": "38535862", "name": "J. D. Jarvis"}]}
我正在嘗試找到一種方法來制作包含 AuthorID 和 Name 列的 excel 文件。 請讓我知道是否有人可以幫助我如何使用 Python 做到這一點。
使用Pandas :
import pandas as pd
df = pd.DataFrame(
[
data
for link in links
for data in link["data"]
]
)
df.rename(columns={"authorId": "AuthorId", "name": "Name"}).to_csv("data.csv")
例如,您可以執行以下操作:
dics = [
{"total": 1, "offset": 0, "data": [{"authorId": "118985833", "name": "Krystle K. Madrid"}]},
{"total": 1, "offset": 0, "data": [{"authorId": "107707217", "name": "S. N. Kirnon"}]},
{"total": 5, "offset": 0, "data": [{"authorId": "121754802", "name": "Jason L. Jarvis"}, {"authorId": "143879405", "name": "J. Jarvis"}, {"authorId": "145088127", "name": "J. Jarvis"}, {"authorId": "31259897", "name": "J. W. Jarvis"}, {"authorId": "38535862", "name": "J. D. Jarvis"}]}
]
df = pd.DataFrame(columns = ['AuthorID','Name'])
for d1 in dics:
for d2 in d1["data"]:
df = pd.concat([df,
pd.DataFrame({"AuthorID":[d2["authorId"]],
"Name":[d2["name"]]})],
ignore_index=True)
結果:
AuthorID Name
0 118985833 Krystle K. Madrid
1 107707217 S. N. Kirnon
2 121754802 Jason L. Jarvis
3 143879405 J. Jarvis
4 145088127 J. Jarvis
5 31259897 J. W. Jarvis
6 38535862 J. D. Jarvis
具有相同結果的類似循環:
for d1 in dics:
d_new = {"AuthorID":[d2["authorId"] for d2 in d1["data"]],
"Name":[d2["name"] for d2 in d1["data"]]}
df = pd.concat([df,pd.DataFrame(d_new)],ignore_index=True)
這是一個單行解決方案:
df = pd.DataFrame({"AuthorID":[d2["authorId"] for d1 in dics for d2 in d1["data"]],
"Name":[d2["name"] for d1 in dics for d2 in d1["data"]]})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.