翻譯|行業(yè)資訊|編輯:吉煒煒|2025-09-01 14:01:44.487|閱讀 29 次
概述:Aspose.Cells for Python 提供了豐富的 JSON 到 Excel 轉(zhuǎn)換流程,您可以輕松地將其與 Pandas 集成,以獲取干凈的 DataFrame 進(jìn)行分析。在本篇教程中,您將學(xué)習(xí)如何在 Python 中將 JSON 轉(zhuǎn)換為 Pandas DataFrame。
# 界面/圖表報(bào)表/文檔/IDE等千款熱門(mén)軟控件火熱銷(xiāo)售中 >>
相關(guān)鏈接:
在數(shù)據(jù)分析、報(bào)告和 ETL 流程中,使用 JSON 和 Pandas DataFrame 非常常見(jiàn)。雖然 Pandas 提供了read_json基本的解析功能,但它在處理深度嵌套結(jié)構(gòu)、超大文件或 Excel 優(yōu)先工作流時(shí)可能會(huì)遇到困難。Aspose.Cells for Python 提供了豐富的 JSON 到 Excel 轉(zhuǎn)換流程,您可以輕松地將其與 Pandas 集成,以獲取干凈的 DataFrame 進(jìn)行分析。在本篇教程中,您將學(xué)習(xí)如何在 Python 中將 JSON 轉(zhuǎn)換為 Pandas DataFrame。
加入Aspose技術(shù)交流QQ群(1041253375),與更多小伙伴一起探討提升開(kāi)發(fā)技能。
Aspose.Cells for Python via .NET是一款功能強(qiáng)大的電子表格 API,無(wú)需 Microsoft Excel。除了傳統(tǒng)的 Excel 自動(dòng)化功能外,它還支持直接導(dǎo)入和導(dǎo)出 JSON,非常適合將 JSON 轉(zhuǎn)換為 Pandas DataFrame,然后在 Excel 中保存或處理。
使用 Aspose.Cells,您可以:
簡(jiǎn)而言之,該庫(kù)可以輕松地將數(shù)據(jù)從 JSON 格式遷移到 Excel 中用于報(bào)告,同時(shí)您可以使用 Pandas 進(jìn)行更深入的分析。它將JsonUtilityJSON 導(dǎo)入工作表,并JsonLayoutOptions控制數(shù)組和嵌套對(duì)象的擴(kuò)展方式。
Aspose.Cells 直接將 JSON 導(dǎo)入工作表。然后讀取標(biāo)題行和數(shù)據(jù)行,構(gòu)建 Pandas DataFrame。
按照以下步驟將 JSON 轉(zhuǎn)換為 pandas DataFrame:
以下代碼示例展示了如何在 Python 中將 JSON 轉(zhuǎn)換為 pandas DataFrame:
import pandas as pd import aspose.cells as ac # Create a new workbook and get the first worksheet (0-based index) wb = ac.Workbook() ws = wb.worksheets.get(0) # Configure how JSON should be laid out in the worksheet options = ac.utility.JsonLayoutOptions() options.array_as_table = True # Treat a top-level JSON array as a table (rows/columns) # Example JSON array of simple objects json_data = '[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]' # Import JSON into the worksheet starting at row=0, col=0 (cell A1) ac.utility.JsonUtility.import_data(json_data, ws.cells, 0, 0, options) # Locate the first row that contains data (this will be our header row) header_idx = ws.cells.min_data_row # Extract header values from that row to use as DataFrame column names columns = [cell.value for cell in ws.cells.rows[header_idx]] # Extract all subsequent rows as data (skip the header row) data = [ [cell.value for cell in row] for idx, row in enumerate(ws.cells.rows) if row and idx != header_idx ] # Build the DataFrame using the collected headers and rows df = pd.DataFrame(data, columns=columns) # Display the result print(df)輸出:
id name 0 1.0 Alice 1 2.0 Bob
如果您的 JSON 包含嵌套對(duì)象,Aspose.Cells 會(huì)使用 JsonUtility 將 JSON 導(dǎo)入工作表,然后您可以將其導(dǎo)出到 DataFrame。JsonLayoutOptions 控制數(shù)組和嵌套對(duì)象的展開(kāi)方式。
按照以下步驟將嵌套 JSON 轉(zhuǎn)換為 pandas DataFrame:
以下代碼示例展示了如何在 Python 中將嵌套 JSON 轉(zhuǎn)換為 pandas DataFrame:
import pandas as pd import aspose.cells as ac # Create Workbook and get first worksheet wb = ac.Workbook() ws = wb.worksheets.get(0) # Layout options for nested JSON opt = ac.utility.JsonLayoutOptions() opt.array_as_table = True # Treat 'orders' array as a table (rows) opt.ignore_array_title = True # Do not place a title row for the 'orders' array opt.ignore_object_title = True # Do not place extra title rows for nested objects (e.g., 'buyer') opt.kept_schema = True # Keep a stable set of columns even if some records miss fields # Step 3: Your nested JSON nested = ''' { "batch": "A1", "orders": [ {"orderId": "1001", "total": "49.90", "buyer": {"city": "NYC", "zip": "10001"}}, {"orderId": "1002", "total": "79.00", "buyer": {"city": "Boston", "zip": "02108"}} ] } ''' # Import at A1 (row=0, col=0) using the options above ac.utility.JsonUtility.import_data(nested, ws.cells, 0, 0, opt) # Detect used range first_row = ws.cells.min_data_row first_col = ws.cells.min_data_column last_row = ws.cells.max_data_row last_col = ws.cells.max_data_column # Read header row across the full used column span (fixed width) raw_columns = [ws.cells.get(first_row, c).value for c in range(first_col, last_col + 1)] # Make headers safe: replace None/blank with "Column{n}" and cast to str columns = [ (str(v) if v is not None and str(v).strip() != "" else f"Column{idx + 1}") for idx, v in enumerate(raw_columns) ] # Read data rows across the same span (fixed width guarantees alignment) data = [] for r in range(first_row + 1, last_row + 1): row_vals = [ws.cells.get(r, c).value for c in range(first_col, last_col + 1)] data.append(row_vals) # Build DataFrame df = pd.DataFrame(data, columns=columns) # Optional: tidy up column names (e.g., replace spaces) df.columns = [str(c).strip() for c in df.columns] # Optional typing: # - Keep ZIPs as strings (leading zeros matter) # - Convert totals to numeric (coerce non-numeric to NaN) for col in list(df.columns): if col.lower().endswith("total"): df[col] = pd.to_numeric(df[col], errors="coerce") # Print print(df)輸出:
A1 1001 49.90 NYC 10001 0 None 1002 79.00 Boston 02108
注意:如果啟用convert_numeric_or_date=True,看起來(lái)像數(shù)字的字符串(例如總數(shù))可能會(huì)轉(zhuǎn)換為數(shù)字,但郵政編碼(例如)"02108"可能會(huì)丟失前導(dǎo)零。False如果您需要將郵政編碼轉(zhuǎn)換為字符串,請(qǐng)保留此選項(xiàng)。
使用 Aspose.Cells 將任意 Excel 范圍導(dǎo)出為 JSON,然后將該 JSON 作為 DataFrame 加載到 Pandas 中。當(dāng)您需要為服務(wù)或管道進(jìn)行結(jié)構(gòu)化 JSON 交接時(shí),此功能非常有用。
按照以下步驟通過(guò) JSON 將 Excel 轉(zhuǎn)換為 pandas DataFrame:
以下代碼示例展示了如何在 Python 中通過(guò) JSON 將 Excel 轉(zhuǎn)換為 pandas DataFrame:
import io import pandas as pd from aspose.cells.utility import JsonUtility # JSON export utility from aspose.cells import Workbook, JsonSaveOptions, License # Create a new workbook and access the first worksheet workbook = Workbook() worksheet = workbook.worksheets.get(0) # Get the cells of the worksheet cells = worksheet.cells # Populate a small table (headers + rows) cells.get("A1").value = "Name" cells.get("B1").value = "Age" cells.get("C1").value = "City" cells.get("A2").value = "Alice" cells.get("B2").value = 25 cells.get("C2").value = "New York" cells.get("A3").value = "Bob" cells.get("B3").value = 30 cells.get("C3").value = "San Francisco" cells.get("A4").value = "Charlie" cells.get("B4").value = 35 cells.get("C4").value = "Los Angeles" # Set up JSON save options (defaults are fine for a simple table) json_save_options = JsonSaveOptions() # Export the used range to a JSON string # max_display_range grabs the full rectangular region that contains data json_text = JsonUtility.export_range_to_json(cells.max_display_range, json_save_options) # Read the JSON string into a Pandas DataFrame # Pandas can parse a JSON string directly df = pd.read_json(io.StringIO(json_text)) # Use the DataFrame print(df)輸出:
Name Age City 0 Alice 25 New York 1 Bob 30 San Francisco 2 Charlie 35 Los Angeles
使用 Aspose.Cells for Python,將 JSON 轉(zhuǎn)換為 Pandas DataFrames 變得非常簡(jiǎn)單。您可以獲得可靠的嵌套結(jié)構(gòu)處理、模式穩(wěn)定性選項(xiàng),以及在需要時(shí)輕松導(dǎo)出到 Excel 的途徑。將 Pandas 的靈活性與 Aspose.Cells 中的 JSON/Excel 管道相結(jié)合,簡(jiǎn)化數(shù)據(jù)處理并解鎖強(qiáng)大的 Python 分析功能。
————————————————————————————————————————
關(guān)于慧都科技:
慧都科技是專(zhuān)注軟件工程、智能制造、石油工程三大行業(yè)的數(shù)字化解決方案服務(wù)商。在軟件工程領(lǐng)域,我們提供開(kāi)發(fā)控件、研發(fā)管理、代碼開(kāi)發(fā)、部署運(yùn)維等軟件開(kāi)發(fā)全鏈路所需的產(chǎn)品,提供正版授權(quán)采購(gòu)、技術(shù)選型、個(gè)性化維保等服務(wù),幫助客戶(hù)實(shí)現(xiàn)技術(shù)合規(guī)、降本增效與風(fēng)險(xiǎn)可控。慧都科技Aspose在中國(guó)的官方授權(quán)代理商,提供Aspose系列產(chǎn)品免費(fèi)試用,咨詢(xún),正版銷(xiāo)售等于一體的專(zhuān)業(yè)化服務(wù)。Aspose是文檔處理領(lǐng)域的優(yōu)秀產(chǎn)品,幫助企業(yè)高效構(gòu)建文檔處理的應(yīng)用程序。
下載|體驗(yàn)更多Aspose產(chǎn)品,請(qǐng)咨詢(xún),或撥打產(chǎn)品熱線(xiàn):023-68661681
加入Aspose技術(shù)交流QQ群(1041253375),與更多小伙伴一起探討提升開(kāi)發(fā)技能。
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請(qǐng)務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請(qǐng)郵件反饋至chenjj@fc6vip.cn
文章轉(zhuǎn)載自:慧都網(wǎng)